This script was created by my brother Scott Prudence and I, this snapshot’s 1 specific volume then once the snapshot is completed the script then removes the oldest snapshot. This is a way of implementing a weekly snapshot of a single volume within AWS.
NOTE – Change the VOLUMEID variable from vol-xxxxxx to your volume ID
#! /bin/bash # Set the variables DATE="$(date +"%d-%m-%y")" DESCRIPTION="Web server backup - $DATE" VOLUMEID="vol-xxxxxx" BACKUPSTOKEEP="1" # Run the backup SNAPSHOTID=$(aws ec2 create-snapshot --volume-id $VOLUMEID --description "$DESCRIPTION" --output text --query "SnapshotId") echo "Waiting for Snapshot ID: $SNAPSHOTID" SNAPSHOTPROGRESS=$(aws ec2 describe-snapshots --snapshot-ids $SNAPSHOTID --query "Snapshots[*].Progress" --output text) while [ $SNAPSHOTPROGRESS != "100%" ] do sleep 15 echo "Snapshot ID: $SNAPSHOTID $SNAPSHOTPROGRESS" SNAPSHOTPROGRESS=$(aws ec2 describe-snapshots --snapshot-ids $SNAPSHOTID --query "Snapshots[*].Progress" --output text) done # Delete the oldest backup NUMBEROFBACKUPS="$(aws ec2 describe-snapshots --filters Name=volume-id,Values=$VOLUMEID --query 'Snapshots[].[SnapshotId]' | wc -l)" if [ $NUMBEROFBACKUPS -gt $BACKUPSTOKEEP ] then SNAPSHOTID=$(aws ec2 describe-snapshots --filters Name=volume-id,Values=$VOLUMEID --query 'Snapshots[].[StartTime,SnapshotId]' --output text | sort -n | head -1 | awk '{print $2}') echo "Deleting oldest backup - $SNAPSHOTID" aws ec2 delete-snapshot --snapshot-id $SNAPSHOTID else echo "The only backup that exists was just created, not deleting any backups..." fi
Leave a Reply