Skip to content

Instantly share code, notes, and snippets.

@sechiro
Last active December 22, 2015 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sechiro/7cf0f42a81e50b601b62 to your computer and use it in GitHub Desktop.
Save sechiro/7cf0f42a81e50b601b62 to your computer and use it in GitHub Desktop.
Amazon公式、Canonical公式と自分のAMIの一覧を出力するスクリプト(出力を300秒キャッシュ)
#!/bin/bash
set -ue
prefix=`basename $0`
timestamp_file=/tmp/$prefix.timestamp
cache_file=/tmp/$prefix.cache
timestamp=`date '+%s'`
cache_time=300
if [ "${1:-''}" = "nocache" ];then
cache_time=0
fi
describe_images(){
echo $timestamp > $timestamp_file
# 099720109477: canonical
aws ec2 describe-images \
--owners self amazon 099720109477 \
--filters \
Name=virtualization-type,Values=hvm \
Name=root-device-type,Values=ebs \
Name=architecture,Values=x86_64 \
Name=block-device-mapping.volume-type,Values=standard
}
# 出力を括弧でまとめる
(
if [ -e $timestamp_file ];then
cache_timestamp=`cat $timestamp_file`
# キャッシュファイルが有効期間を過ぎている場合はAWSから読み出してキャッシュファイルにも書く
if [ $timestamp -gt `expr $cache_timestamp + $cache_time` ];then
describe_images | tee $cache_file
else
# キャッシュファイルが有効期間内の場合はキャッシュファイルを読み出すだけ
cat $cache_file
fi
# キャッシュファイルがない場合
else
describe_images | tee $cache_file
fi
) | jq -r '.Images | sort_by(.Name)| .[] | select(.Platform != "windows") | .Name + ": " + .ImageId'
@sechiro
Copy link
Author

sechiro commented Nov 12, 2014

Usage sample: Latest Ubuntu trusty(14.04) AMI ID

latest_ami=`./get-aws-ec2-images.sh | grep ubuntu-trusty | grep -v -e milestone -e testing | sort -r | head -n1 | cut -d' ' -f2`

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