If you have a nightly snapshot schedule for your volumes that are attached on an AWS storage gateway or ec2 instances you will start to incur higher charges as the number of snapshots increase over time. Instead of deleting them manually you can use the following bash script to automatically delete snapshots when they reach a specific number.
Prerequisites:
AWS CLIBashPurge Snapshot bash script
#!/bin/bash
## version 1.1
###Set the number of snapshots you would like to keep in the snapshot_count variable.
snapshot_count="42"
profile="ops-or"
region="us-west-2"
owner="12345678"
# Get array of snapshot IDs sorted by age (oldest to newest)
snapshots=($(/usr/local/bin/aws --profile $profile --region $region ec2 describe-snapshots --owner-ids $owner --filters Name=description,Values=*-snapshot --query 'Snapshots[*].[StartTime,SnapshotId]' --output text | sort -n | awk '{print $2}'))
# Get number of snapshots
count=${#snapshots[@]}
if [[ "$count" -lt "$snapshot_count" ]]; then
echo "We already have less than $snapshot_count snapshots"
exit 0
else
# Drop the last (newest) $snapshot_count IDs from the array
num="$((count - snapshot_count))"
snapshots=(${snapshots[@]:0:$num})
# Loop through the remaining snapshots and delete
for snapshot in ${snapshots[@]}; do
/usr/local/bin/aws ec2 delete-snapshot --snapshot-id $snapshot --profile $profile --region $region
done
fi
Tagged With: AWS, snapshot, storage gateway
Facebook Comments