Sometimes, developers create EC2 instances with volumes attached to them by default. For backup purposes, these developers also create snapshots. However, when they no longer need the EC2 instance and decide to terminate it, they sometimes forget to delete the snapshots created for backup. As a result, they continue to incur costs for these unused snapshots, even though they are not actively using them.
- We’re using AWS to save money on storage costs. We made a Smart Lambda function that looks at our snapshots and our EC2 instances.
- If Lambda finds a snapshot that isn’t connected to any active EC2 instances, it deletes it to save us money. This helps us keep our AWS costs down.
There are many similar problems like this. For instance, we might attach an Elastic IP to our EC2 instance but forget to delete the Elastic IP after terminating the EC2 instance. In such a case, the Elastic IP continues to incur costs for us.
6. Next, click on ‘Snapshots,’ and then click the ‘Create Snapshot’ button. It will prompt you with a page that looks like this.
8. Next, click ‘Next,’ provide a name for your Snapshot, and then scroll down and click ‘Create Snapshot’.
4. Select ‘Author from Scratch,’ then enter the Function name, and choose the latest Python version.
9. Click ‘Deploy’ to save your changes, and then click ‘Test.’ It will prompt a page that looks like the one given below.
10. Please configure the settings as displayed above and then scroll down. Next, click on ‘Create Event’.
11. Once you’ve created the event, proceed to the IAM Console(Identity and Access Management) and then navigate policies section to create a new policy.
13. In the ‘Actions’ section, grant permissions for the following actions: DescribeInstances, DescribeVolumes, DescribeSnapshots, DeleteSnapshots.
15. Next, go to the page of the Lambda function you’ve created. In the “Permissions” section, click on the role name.
19. After that, you can go to the Lambda function page and run the code; it will display some outputs as shown below.
5. As expected, our Lambda function deleted the snapshot because it was associated with a volume that couldn’t be found.
- We can use CloudWatch to automatically trigger the Lambda function every hour, day, minute, or second. However, this may result in higher costs because our Lambda execution time increases when triggered automatically.
- Nevertheless, manually triggering this function is a better choice because it allows us to trigger it when needed.