How to find AMI ID of CentOS 7 image in AWS Marketplace?

bandjalong picture bandjalong · Nov 28, 2016 · Viewed 30.7k times · Source

I have been launching EC2 instances by logging in to the AWS site, hitting the "Launch" button and following the proscribed steps. Now I'd like to launch instance from an Ansible script, and to do this I (think I) need the AMI ID of the image I wish to launch.

The problem is that I am launching an image from the "Marketplace", and I cannot find the AMI ID. In particular I'm using the Centos 7 image. This is easy to find in the web interface, just go to the marketplace and search for "centos", the image I want is the first one found, but the information provided about the image doesn't seem to include the AMI ID that I need to launch it from a script. The workaround is to manually launch an image, and then when inspecting the running image, the AMI ID is given. But is there an easier way to find it?

Answer

Anthony Neace picture Anthony Neace · Nov 28, 2016

CentOS publishes their AMI product codes to their wiki. The wiki provides the following information for the latest CentOS 7 AMI:

  • Owner: aws-marketplace
  • Product Code: aw0evgkw8e5c1q413zgy5pjce

Using this information, we can query describe-images with the AWS CLI:

Example:

aws ec2 describe-images \
    --owners 'aws-marketplace' \
    --filters 'Name=product-code,Values=aw0evgkw8e5c1q413zgy5pjce' \
    --query 'sort_by(Images, &CreationDate)[-1].[ImageId]' \
    --output 'text'

Output:

ami-6d1c2007

This query returns a single AMI ID, selected by sorting the collection by creation date and then selecting the last (most recent) element in the collection.

Per the CentOS wiki, multiple AMI ids may be associated with a product key, so while this query would currently only return a single AMI because only one matching this product currently exists... in the future if a new AMI is created for this product code for any reason this query will return it instead.