Developers sometimes create EC2 instances with attached volumes and take snapshots for backup. When these instances are terminated, they often forget to delete the snapshots, leading to unnecessary storage costs.
We use AWS to reduce storage costs with a Smart Lambda function. This function checks all snapshots and EC2 instances, and if it finds any snapshots not connected to active EC2 instances, it deletes them. This helps us save money by eliminating unused snapshots.
- Log into your AWS Console.
- Navigate to the EC2 Console.
- In the Instances section, select 'Instances,' and then click on 'Launch Instance'.
- Next, navigate to the 'Elastic Block Store' section and select 'Volumes'.
- You will notice that a default volume has already been created for us.
- Next, click on 'Snapshots,' and then click the 'Create Snapshot' button.
- In Volume ID section choose your default Volume ID created when we create instance.
- Next, click 'Next,' provide a name for your Snapshot, and then scroll down and click 'Create Snapshot'.
- After creating a Snapshot, navigate to the Lambda Console and create the function.
- Next, clear the existing code and replace it with the 'ebs-stale-snapshot.py' code.
- Click 'Deploy' to save your changes, and then click 'Test.' It will prompt a page that looks like the one given below.
- Next, click on 'Create Event'. 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.
- In the 'Actions' section, grant permissions for the following actions: DescribeInstances, DescribeVolumes, DescribeSnapshots, DeleteSnapshots.
- Then scroll down and click 'Add Permissions'.
- You can terminate the EC2 instance to test our Lambda function. Under the Code section, click 'Test code', it will display an output like this.