Identifying, Copying and Encrypting a Private AMI Using boto3

Eloisa Tovee 2nd March 2020

Recently our team had a requirement to copy the latest Amazon Linux 2 AMI locally, ensuring it was private and encrypted.

This blog describes the two steps we took to tackle this challenge. We’ll also provide a repository containing code which can be re-used if you face a similar challenge.

Part 1: Identify the Latest Amazon Linux 2 AMI

The first part of the solution involved using boto3 to return a list of images. Using the trusty boto3 EC2 documentation we could see that there was a describe_images() request that met our needs. By using Filters within this request, we could list the AMIs that were relevant to us.

We required two filters – one was the name of the AMI. We wanted an Amazon Linux 2 AMI with HVM virtualisation, as we knew this worked for us. Therefore, our first filter was ‘amzn2-ami-hvm-2.0*’. We also only wanted AMIs which were owned by Amazon, so our next filter was to use the Amazon ownership ID: ‘137112412989’. In the repository, both can be found in the file.

We could now populate the describe_images() request with our filters, but how were we going to sort them by date order? We decided to use the built-in sorted() functionality and sorted it in reverse order based on the ‘CreationDate’ of the AMIs.

Finally, we returned item number one on our list. The latest version of the Amazon owned Linux 2 AMI.

Part 2: Copy the AMI Whilst Encrypting it and Making it Private

Now that we have a function returning the latest Linux 2 AMI, we needed to copy that AMI onto our account and encrypt it. Again, we looked at the boto3 documentation and found that there was a copy_image() command which met our needs.

The copy_image() command has four required parameters – the Name and the SourceImageID of the AMI you wish to copy can be taken from the details of the previous request. The SourceRegion we have been using is ‘eu-west-1’ as default. The Encrypted parameter is a Boolean, and given one of our requirements is to encrypt the AMI, we will be setting this to true.

This is a very simple solution to solve what is likely to be a common problem for many people. If you’d like to check out the code then you can find it in the ECS Digital repository (looks a little like the below…)


Found this interesting? Why not share it: