How to List all AMIs for each region in AWS

A current project required a list of Amazon Machine Images (AMIs) for all regions for use in terraform. I couldn’t find a script to do this for me, so here you will find one that uses the aws cli, jq and a bit of Bash.

To use it, simply pass the full name of the image you want to find in each region. This must be unique or else it will just pick the first AMI. For example:

$ ./images.sh RHEL-7.4_HVM_GA-20170808-x86_64-2-Hourly2-GP2
"ap-south-1" = "ami-e41b618b"
"eu-west-3" = "ami-39902744"
"eu-west-2" = "ami-a1f5e4c5"
"eu-west-1" = "ami-bb9a6bc2"
"ap-northeast-2" = "ami-0f5a8361"
"ap-northeast-1" = "ami-30ef0556"
"sa-east-1" = "ami-a789ffcb"
"ca-central-1" = "ami-dad866be"
"ap-southeast-1" = "ami-10bb2373"
"ap-southeast-2" = "ami-ccecf5af"
"eu-central-1" = "ami-d74be5b8"
"us-east-1" = "ami-c998b6b2"
"us-east-2" = "ami-cfdafaaa"
"us-west-1" = "ami-66eec506"
"us-west-2" = "ami-9fa343e7"

The script is below:

#!/bin/bash
if [ -z "$1" ] ; then
    echo "Please pass the name of the AMI"
    exit 1
fi

IMAGE_FILTER="${1}"

declare -a REGIONS=($(aws ec2 describe-regions --output json | jq '.Regions[].RegionName' | tr "\\n" " " | tr -d "\\""))
for r in "${REGIONS[@]}" ; do
    ami=$(aws ec2 describe-images --query 'Images[*].[ImageId]' --filters "Name=name,Values=${IMAGE_FILTER}" --region ${r} --output json | jq '.[0][0]')
    printf "\\"${r}\\" = ${ami}\\n"
done

EMail

web@WinderResearch.com

Registered Address

Winder Research and Development Ltd.,

Adm Accountants Ltd, Windsor House,

Cornwall Road,

Harrogate,

North Yorkshire,

HG1 2PW,

UK

Registration Number

08762077

VAT Number

GB214263735
© Winder Research and Development Ltd. 2016-2018; all rights reserved.