Talk Nerdy To Me: Amazon EC2 backup pruning script

Update: here’s a text version without smartquotes. Download it, change the extension to .sh, and enjoy.

As a followup to this previous post – a script that automates EBS snapshots on an Amazon EC2 server – here’s a bash script to prune the EC2 snapshots created by the other script.

#!/bin/bash
export EC2_PRIVATE_KEY={path to your AWS private key} 
export EC2_CERT={path to your AWS certificate} 
export JAVA_HOME=/usr/lib/jvm/jre
export EC2_HOME=/opt/aws/apitools/ec2

VOLUME_ID=`/opt/aws/bin/ec2-describe-volume-status | cut -f 2 | grep -e “vol-[[:xdigit:]]\{8\}”`
echo Volume ID is $VOLUME_ID

SNAPSHOT_ID=`/opt/aws/bin/ec2-describe-snapshots –filter volume-id=$VOLUME_ID –filter description=”Weekly backup” | sort -r -k 5 | sed 1,2d | cut -f 2`
echo Snapshot ID to delete is $SNAPSHOT_ID

/opt/aws/bin/ec2-delete-snapshot $SNAPSHOT_ID
echo Snapshot deleted

This finds and deletes the oldest snapshot with a description “Weekly backup” (you’ll need to change that if your automated backup script generates a different description), while always keeping the two newest snapshots. If you want to keep more snapshots, change the sed command: changing it from sed 1,2d to sed 1,5d will keep the five most recent snapshots instead of the two most recent.

European elections? What European elections? Never heard of ’em. 

This entry was posted in Miscellaneous. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *