Shell script to automatically remove old AWS Lightsail snapshots (and retain a specific number of backups)

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.

Requirements

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

 

Bash Script

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.

 

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:

https://github.com/JozefJarosciak/Lightsail-Backup-and-Clean-Up-Shell-Script

 

Enjoy!