Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alexgleith/1cf195acbad789c42c5ca1510b3d8358 to your computer and use it in GitHub Desktop.
Save alexgleith/1cf195acbad789c42c5ca1510b3d8358 to your computer and use it in GitHub Desktop.
When run from an EC2 instance this snippet will return the CURRENT ami id for Amazon Linux in the REGION that the instance is running in and load it up into a variable called currentAMI.
#!/bin/bash -xe
# grab the Availability Zone from the Meta Data service
az=$(curl http://169.254.169.254/latest/meta-data/placement/availability-zone/)
# drop the trailing zone to get the REGION the instance is running in.
currentRegion=${az%?}
# retirve the source AMI (latest Amazon Linux image in this case)
currentAMI=$(aws ec2 describe-images --owners self amazon --filters "Name=name,Values=amzn-ami-hvm-*gp2" --query 'Images[].[CreationDate,ImageId]' --output text --region $currentRegion | sort -k1 | tail -n1 | awk '{print $2}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment