In the first post, I have explained how to schedule nightly backups of Amazon Lightsail Instance by leveraging AWS Command Line Interface (CLI). In this post, I’ll show you how to create a bash file that can be scheduled to remove old AWS Lightsail snapshots and retain only a specific number of snapshots in your account.
Make sure that you have installed JQ from https://stedolan.github.io/jq/ . You can always do so by running the following command: sudo yum install jq
Assuming you only have a single instance running in your Lightsail account, you can schedule the following bash script as a cron job to do your old snapshot clean up automatically.
Note: Adjust variable snapshotsToKeep to whatever number of snapshots you’d like to keep.
#!/bin/bash # Author: Jozef Jarosciak # Set number of snapshots you'd like to keep snapshotsToKeep=5 # get the total number of available Lightsail snapshots numberOfSnapshots=$(aws lightsail get-instance-snapshots | jq '.|length') # get the names of all snapshots sorted from old to new SnapshotNames=$(aws lightsail get-instance-snapshots | jq '. | sort_by(.createdAt) | ..name') # loop through all snapshots while IFS= read -r line do let "i++" # delete old snapshot condition if (($i <= $numberOfSnapshots-$snapshotsToKeep)) then snapshotToDelete=$(echo "$line" | tr -d '"') # delete snapshot now aws lightsail delete-instance-snapshot --instance-snapshot-name $snapshotToDelete echo "Deleted Snapshot: " + $line fi done <<< "$SnapshotNames" exit 1
This is how I have it setup. I’ve created a file called: aws-snapshot.sh in my /home/ec2-user directory and created a cron job to execute it twice a day to first create a new snapshot backup and then delete the old snapshot backups.
Here is a post that shows you: How to schedule nightly backups of Amazon Lightsail Instance by leveraging AWS Command Line Interface (CLI)
This script is now available on Github if you’d like to contribute your changes: