Skip to content

Instantly share code, notes, and snippets.

@vancluever
Created January 26, 2016 08:05
Show Gist options
  • Star 60 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save vancluever/7676b4dafa97826ef0e9 to your computer and use it in GitHub Desktop.
Save vancluever/7676b4dafa97826ef0e9 to your computer and use it in GitHub Desktop.
Find the most recent Ubuntu AMI using aws-cli (or any other AMI for that matter)
#!/bin/sh
# Use AWS CLI to get the most recent version of an AMI that
# matches certain criteria. Has obvious uses. Made possible via
# --query, --output text, and the fact that RFC3339 datetime
# fields are easily sortable.
export AWS_DEFAULT_REGION=us-east-1
aws ec2 describe-images \
--filters Name=name,Values=ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64* \
--query 'Images[*].[ImageId,CreationDate]' --output text \
| sort -k2 -r \
| head -n1
@rodriguez-matias
Copy link

nice, thanks!

@tdmalone
Copy link

⚠️ A lot of the examples above don't use --owners to limit the account ID to one known to be owned by Canonical. This is a security risk, as anyone can make - and publicly share - an AMI with a similar name, with who-knows-what installed in it.

@stephenlauck
Copy link

To just get "ubuntu jammy" and the latest AMI id only:

aws ec2 describe-images --owners 099720109477 --filters 'Name=name,Values=ubuntu/images/hvm-ssd/ubuntu-jammy*' --query 'sort_by(Images, &CreationDate)[-1].[ImageId]' --output text

@zainulabidin302
Copy link

zainulabidin302 commented Sep 17, 2023

Only image id with same original command:

AMI_ID=`aws ec2 describe-images \
 --filters 'Name=name,Values=ubuntu/images/hvm-ssd/ubuntu-*' \
 --query 'Images[*].[ImageId,CreationDate]' --output text \
 | sort -k1 -r \
 | head -n1 | cut -f 1 -w`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment