Bootstrap FreeKB - Amazon Web Services (AWS) - Create Amazon Machine Images (AMI) using Python boto3
Amazon Web Services (AWS) - Create Amazon Machine Images (AMI) using Python boto3


This assumes you are familar with the basic configurations needed to connect to Amazon Web Services (AWS) using Python boto3. If not, check out my article Python (Scripting) - Getting Started with Amazon Web Services (AWS) boto3.

There are different ways to go about backing up your Amazon Web Services (AWS) EC2 instances

An AMI will be a complete snapshot of the entire EC2 instance, whereas an EBS Volume Snapshot will be a snapshot of one of the EBS Volumes being used by the EC2 instance

Here is the minimal boilerplate code without any error handling to create an Amazon Machine Image (AMI) from one of your EC2 instances. This will use the default profile in your .aws/credentials profile. If you want to used a named profile, check out my article Python (Scripting) - Getting Started with Amazon Web Services (AWS) boto3. Be aware that by default, this will stop the EC2 instance, then create the AMI, and then start the EC2 instance.

#!/usr/bin/python3
import boto3

client = boto3.client('ec2')
response = client.create_image(
        InstanceId='i-0a3ea97aa2383de58',
        Name='my AMI'
)
print(response)

 

The NoReboot option can be used to create the AMI snapshot without rebooting the EC2 instance

#!/usr/bin/python3
import boto3

client = boto3.client('ec2')
response = client.create_image(
        InstanceId='i-0a3ea97aa2383de58',
        Name='my AMI',
        NoReboot=True,
)
print(response)

 

Here is a more practical example, with try/except/else error handling.

#!/usr/bin/python3
import boto3
import sys

try:
  client = boto3.client('ec2')
except Exception as exception:
  print(exception)
  sys.exit(1)

try:
  response = client.create_image(
        InstanceId='i-0a3ea97aa2383de58',
        Name='my AMI'
  )
except Exception as exception:
  print(exception)
else:
  print(f"response = {response}")

 

Which should return something like this.

{
  'ImageId': 'ami-0a88a5392e4b1c74d', 
  'ResponseMetadata': {
    'RequestId': 'dbee200b-0f54-4642-9bbd-bba69c98e602', 
    'HTTPStatusCode': 200, 
    'HTTPHeaders': {
      'x-amzn-requestid': 'dbee200b-0f54-4642-9bbd-bba69c98e602', 
      'cache-control': 'no-cache, no-store', 
      'strict-transport-security': 'max-age=31536000; includeSubDomains', 
      'content-type': 'text/xml;charset=UTF-8', 
      'content-length': '242', 
      'date': 'Mon, 15 Apr 2024 06:12:31 GMT', 
      'server': 'AmazonEC2'
    }, 
    'RetryAttempts': 0
  }
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 9255f4 in the box below so that we can be sure you are a human.