🚀AWS Cloud Cost Optimization

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.

image

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.

image

Step :4 Use the below Python code:

image

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

image

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:

image

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

image

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

image

Name of the policy:

image

Now our role also has this new policy:

image

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:

image

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:

image

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

Kindly feel free to ask any queries in the section below. I'd be pleased to respond to them.

Please follow and use the heart❤❤ button below to express your support if you think this content is helpful 😊.

I appreciate you taking the time to read.