Skip to content

Instantly share code, notes, and snippets.

@rdp-cloud
Created March 31, 2017 22:01
Show Gist options
  • Save rdp-cloud/779a1d714c7815e9de6e254f2802e71b to your computer and use it in GitHub Desktop.
Save rdp-cloud/779a1d714c7815e9de6e254f2802e71b 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