Search code examples
amazon-web-servicesamazon-ec2aws-cliamazon-ami

AWS CLI filter to return unique list of the latests AMIs for a particular AMI name


I'd like to use the AWS CLI to unique list containing only the most recent AMI names

This is my current command, which returns multiple AMI names for each service:

aws ec2 describe-images --owners "<ACCOUNT_ID>" --filters "Name=name,Values=${ami_name}*"  --query 'reverse(sort_by(Images, &CreationDate))[*].Name' --output table

Example output:

-------------------------------------------
|             DescribeImages              |
+-----------------------------------------+
|  service_abc_500 (latest)               |
|  service_xyz_350 (latest)               |
|  service_abc_499                        |
|  service_abc_498                        |
|  service_xyz_349                        |

Desired output:

-------------------------------------------
|             DescribeImages              |
+-----------------------------------------+
|  service_abc_500                        |
|  service_xyz_350                        |

AMI names for a given service will always the same prefix, the only difference would be the unique ID appended to the end of the AMI name, i.e. _500, _350


Solution

  • You can use [-1] instead of [*] in your query to retrieve just the latest item. See: How to filter the output with the --query option

    Heres the example given in the docs:

    The following example retrieves a list of images that meet several criteria. It then uses the --query parameter to sort the output by CreationDate, selecting only the most recent. Finally, it displays the ImageId of that one image.

    $ aws ec2 describe-images \
        --owners amazon \
        --filters "Name=name,Values=amzn*gp2" "Name=virtualization-type,Values=hvm" "Name=root-device-type,Values=ebs" \
        --query "sort_by(Images, &CreationDate)[-1].ImageId" \
        --output text
    

    ami-00ced3122871a4921