Skip to content

Instantly share code, notes, and snippets.

@elocnatsirt
Last active February 9, 2017 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elocnatsirt/45aa25d168e7218fdcc9bc37ffd8833c to your computer and use it in GitHub Desktop.
Save elocnatsirt/45aa25d168e7218fdcc9bc37ffd8833c to your computer and use it in GitHub Desktop.
Simple bash AMI locator
#!/bin/bash
# AMI Locator that grabs the latest image with options you have specified.
#
# Written By: https://github.com/elocnatsirt
# Options:
# -a = AWS_PROFILE to search for images with
# -r = Operating system release (IE 7 for CentOS 7)
# -v = Operating system version (IE CentOS or Ubuntu)
# -p = Product (IE BaseImage)
# -t = Virtualization Type (hvm or paravirtual)
# Extract options and their arguments into variables.
while getopts 'a:r:v:p:t:' OPT; do
case $OPT in
a) aws_profile=$OPTARG;;
r) os_release=$OPTARG;;
v) os_version=$OPTARG;;
p) product=$OPTARG;;
t) virt_type=$OPTARG;;
esac
done
# Set defaults
aws_profile=${aws_profile:=default}
os_release=${os_release:=7}
os_version=${os_version:=CentOS}
product=${product:=BaseImage}
virt_type=${virt_type:=hvm}
# Initialize arrays
ami_ids=()
ami_dates=()
ami_json=`aws --profile ${aws_profile} ec2 describe-images --filters "Name=tag:OS_Release,Values=${os_release}" "Name=tag:OS_Version,Values=${os_version}" "Name=tag:Product,Values=${product}" "Name=virtualization-type,Values=${virt_type}" | jq .`
get_amis=`echo ${ami_json} | jq '.Images[].ImageId' | sed 's/"//g'`
# Search through AMIs and place them into the pre-defined arrays
for ami in $get_amis; do
ami_date=`echo ${ami_json} | jq -c ".Images[] | select(.ImageId | contains (\"${ami}\"))" | jq '.CreationDate' | sed 's/"//g'`
ami_ids+=(${ami})
ami_dates+=(${ami_date})
done
# Get the latest AMI date in the array
IFS=$'\n'
latest_ami_date=`echo "${ami_dates[*]}" | sort -nr | head -n1`
# Match the latest ami date in the date array with the image id in the id array
for ami in "${!ami_dates[@]}"; do
if [[ "${ami_dates[$ami]}" = "${latest_ami_date}" ]]; then
echo "${ami_ids[$ami]}"
fi
done
@elocnatsirt
Copy link
Author

I have updated this to instead only do one AWS CLI call so it is much faster/efficient.

Obviously this depends on your tagging setup, but the base of it will find the latest AMI depending on the filters you inject.

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