Skip to content

Instantly share code, notes, and snippets.

Last active March 30, 2016 08:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Schedule AMI creation and delete 3 days older images.
#---The following is to create AMI of server daily---#
echo "instance-`date +%d%b%y`" > /tmp/ami-name.txt
INSTANCE_ID=$1 #Pass instance id as arguement or change hardcode it here.
aws ec2 create-image --instance-id $INSTANCE_ID --name "`cat /tmp/ami-name.txt`" --description "This is daily auto AMI by Cron" --no-reboot | grep -i ami | awk '{print $2}' > /tmp/ami-id.txt
#---The following is to remove AMIs older than 3 days---#
echo "instance-`date +%d%b%y --date '3 days ago'`" > /tmp/ami-delete.txt
aws ec2 describe-images --filters "Name=name,Values=`cat /tmp/ami-delete.txt`" | grep -i imageid | awk '{ print $2 }' > /tmp/image-id.txt
aws ec2 describe-images --image-ids `cat /tmp/image-id.txt` | grep snap | awk ' { print $4 }' > /tmp/snapshots.txt
aws ec2 deregister-image --image-id `cat /tmp/image-id.txt`
for i in `cat /tmp/snapshots.txt`;do aws ec2 delete-snapshot --snapshot-id $i ; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment