Last active
August 29, 2015 14:07
-
-
Save asselstine/d39530cfaeadeba127a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
VOL_ID=$1 | |
DESCRIPTION=$2 | |
MAX_BACKUPS=$3 | |
ERROR_EMAIL=test@developer.com | |
LOG_FILE=~/aws_vol_backup.log | |
function log { | |
LOG_LINE="`date`: volume($VOL_ID): $1" | |
echo "$LOG_LINE" | |
echo "$LOG_LINE" >> $LOG_FILE | |
} | |
function print_usage { | |
ME=`basename $0` | |
echo "Usage: $ME <volume-id> [ <snapshot description>, <max number of backups> ]" | |
echo "Arguments:" | |
echo -e "\tvolume-id: The AWS EBS volume-id" | |
echo -e "\tsnapshot description: The description to attach to the snapshot" | |
echo -e "\tmax number of backups: Only retain up to this many backups" | |
} | |
log "Starting backup script called with arguments: $1 $2 $3" | |
if [ "$VOL_ID" = "" ]; then | |
>&2 echo "You must pass the volume id to snapshot" | |
print_usage | |
exit 1 | |
fi | |
if [ "$DESCRIPTION" = "" ]; then | |
DESCRIPTION="Snapshot for volume with id $VOL_ID" | |
fi | |
if [ "$MAX_BACKUPS" = "" ]; then | |
MAX_BACKUPS=8 | |
fi | |
PENDING_SNAPSHOTS=`aws ec2 describe-snapshots --filters Name=volume-id,Values=$VOL_ID Name=status,Values=pending` | |
if [ "$PENDING_SNAPSHOTS" = "" ]; then | |
log "No pending snapshots, creating new snapshot with description $DESCRIPTION" | |
aws ec2 create-snapshot --volume-id $VOL_ID --description "$DESCRIPTION" | |
#Now clean up the old snapshots | |
CMD="aws ec2 describe-snapshots --filters Name=volume-id,Values="$VOL_ID" | | |
awk --field-separator '\t' ""'"'{ strp=substr($7,0,length($7)-1); "date -d \""strp"\" +\"%s\"" | getline result; print $6 " " $7 " " result; }'"'"' | | |
sort -r -k 3 | | |
awk '"'"'{ if (a>'$MAX_BACKUPS') { cmd="aws ec2 delete-snapshot --snapshot-id="$1; print cmd; system(cmd); } else { ++a; print "Retaining " $1 " " $2; } }'"'"' -' | |
log "Retaining up to $MAX_BACKUPS snapshots..." | |
eval $CMD | |
else | |
log "Skipping creation; snapshot is pending: $PENDING_SNAPSHOTS" | |
fi | |
log "Completed backup script" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment