AWS Cloud Cost Optimization

Deepika PandeyDeepika Pandey
3 min read

Stale EBS Snapshots

It is our job as devops or cloud engineers to review the cloud's resources and keep an eye out for any superfluous or no longer-used resources. If the developer fails to remove such resources, it could result in excessive charges.

The goal of this project is to develop a Lambda function that, in order to reduce storage costs, will identify and remove EBS snapshots that are no longer connected to any running EC2 instances.

Description:

The Lambda function returns a list of all active EC2 instances (both running and terminated) as well as all EBS snapshots held by the same account ('self'). It verifies that there are no active instances linked to the related volume, if it exists, for every snapshot. It efficiently optimizes storage costs by deleting any outdated snapshots that it detects.

Let's get hands-on with the project:

Step 1: We will create an EC2 instance.

Step 2: When we create an instance a volume is also created with it and attached to that instance.

Step 3: Now we will create a snapshot of the EBS volume of this instance.

We will construct a lambda function that will check and delete any unnecessary snapshots in the event that this instance and any volumes attached to it are erased in the future. However, the user may have taken numerous snapshots and neglected to delete them.

But currently we have only one snapshot of volume, and that volume is attached to the instance right now, so it will not delete the snapshot.

Step :4 Use the below Python code:

First, click on the deploy button to save the code, then click on the test button and create a test event:

Increase the default execution time of our function from 3 to 10 seconds, as it is a bit more code, so 3 seconds are not enough:

But this function has not the permission to describe the EBS volumes, so we will assign permission:

Step 5:We will create new policy for this role so that it can describe EBS volumes

Name of the policy:

Now our role also has this new policy:

Now try to execute the function, but it should not delete the snapshot as a snapshot of volume is currently attached to the EC2 instance:
It gave an error:

Because we are also describing EC2 instances and volumes in our function, update the policy again and test the function, again. This time it just ran successfully but did not delete any snapshots because volume is attached to an instance:

Now delete the instance; it will delete the attached volume as well, Then rerun the lambda function.Now it has deleted our snapshot:

0
Subscribe to my newsletter

Read articles from Deepika Pandey directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Deepika Pandey
Deepika Pandey