Automate the creation and deletion of EC2 snapshots via AWS CLI 2
We're heavily using AWS and we're scripting everything we can. As AWS CLI 2 came out recently we needed to update our scripts.
This script creates a new snapshot and deletes all snapshots older than 2 weeks, for a specific volume.
### create-snapshot-and-cleanup.sh
```bash
#!/bin/bash
DESCRIPTION="example.com"
VOLUME="vol-xxxxxxxxxx"
SNAPSHOT_AGE=$(date +%Y-%m-%d --date '2 weeks ago')
TODAY=$(date +%d-%m-%Y)
echo "Creating new snapshot of volume $VOLUME."
aws ec2 create-snapshot --output text --description "$DESCRIPTION - AutoSnapshot $TODAY" --volume-id $VOLUME >> /dev/null
echo "Deleting snapshots older than: $SNAPSHOT_AGE"
snapshots=$(aws ec2 describe-snapshots --output text --filters Name=volume-id,Values=$VOLUME --query "Snapshots[?StartTime<'$SNAPSHOT_AGE'].SnapshotId")
echo "Snapshots sheduled for deletion: $snapshots"
for snapshot in $snapshots; do
echo "Deleting $snapshot ..."
aws ec2 delete-snapshot --snapshot-id $snapshot
done
```
Zeno Popovici
12 Aug 2021
« Back to post