Obtain AMI Id from name to be used in CFN

In most cases we create custom AMI’s for various reasons like OS hardening, installing and configuring additional software, etc. If you use single AWS account to create the AMI’s and share it with other AWS accounts and use that as part of CloudFormation template, it is required to pass the new AMI Id every time.

AWS Lambda comes handy for easy and elegant solution to get the latest AMI Id based on the AMI name and owner.

Lambda function

Using CFN custom resource, invoke the Lambda function with AMI Name & Owner as parameters.

Invoking Lambda function through CFN

Output of the above mentioned CFN resources can be referenced using Intrinsic Function like ( { “Fn::GetAtt” : [ “GetAMIId” , “Id” ] } )where the AMI Id property needs to be passed in the CFN resource.

This works for all types of images (self, public & private) since the script filters the image using both AMI name & owner. To use specific version of an image pass the full name of the image (e.g. base_web_v1.9.0) for AMIName parameter. If you want to use the latest version of a specific image pass the name without the version string and instead use wildcard (e.g. base_web_v*).

This function works only if the images follow some pattern in its name. Hope you have an automated mechanism to create AMI’s, if not better do that immediately. Packer is a wonderful tool to create images automatically.

Further improvements:

The script can be enhanced to support filters that are based on root device type (ebs/instance-store) and virtualization type (hvm/paravirtual). It’s very easy to extend the script to enable that. As it’s not required for my use case I skipped it.

1 Comment

 Add your comment
  1. Hi,

    Take a look in https://github.com/lucioveloso/cli2cloudformation.

    Maybe, it can do exactly what you are wishing.

Leave a Comment

Your email address will not be published.