Delete unused EBS (Elastic Block Storage) Volumes on AWS using a Lambda Function

Amazon Elastic Block Store (EBS) is an easy-to-use, high-performance block storage service. It is like an external disk that can be attached to an EC2 Instance and used to store our data on it. If the EBS Volumes are not in use and not needed and still available in the account, then you will be charged by AWS for them unnecessarily. To save some cost, we will see the Lambda function which can be used to find and delete such unused EBS Volumes.

Pre-requisites

  1. AWS Account (Create if you don’t have one). 
  2. Basic understanding of EC2 Instance, click here to know more about EC2 Instance.
  3. Basic understanding of Lambda, click here to know more about Lambda Functions.

What will we do?

  1. Login to AWS.
  2. Create a Lambda Function to delete Unused EBS Volumes.

Login to AWS

  1. Click here to go to AWS Login Page.

When we hit the above link, we will see a web page as follows where we are required to login using our login details.

Once we login into AWS successfully, we will see the main console with all the services listed.

Create a Lambda Function to delete Unused EBS Volumes.

Click on the "Services" at the top left, search for "EC2" and go to the main dashboard of EC2.

On the main dashboard of EC2, scroll down and click on "Volumes" under "Elastic Block Storage".

Here, you will see all the EBS Volumes that you have in the selected region. Volumes with the state "available" are unused volumes and are not attached to any of the EC2 Instances. These volumes are safe to delete if they do not have important data or they have no data on them.

Volumes can be deleted from this console, but if there are 100s-1000s of unused volumes, it is better to have some automation in place.

To automate the process of deleting unused volumes we can use "Lambda Functions". Click on "Services" at the top left of the screen and search for "Lambda".

On the main dashboard of Lambda, click on "Create Function". 

Create a function with "Author from Scratch", name the function to be created and choose the Runtime. Here we are going to see a Lambda Function with Python Runtime to automate the process of deleting the unused EBS Volumes. Click on "Create function" to proceed further.

You will see the following screen with the sample function code.

Use the following code to delete the unused EBS Volumes. Delete the existing function code and paste the following code in the function code box. If you do not want to delete the specific unused EBS Volumes, tag them as "Name: DND". The following code will not delete such volumes.

import boto3
ec2 = boto3.resource('ec2',region_name='eu-west-3')
def lambda_handler(event, context):
    for vol in ec2.volumes.all():
        if  vol.state=='available':
            if vol.tags is None:
                vid=vol.id
                v=ec2.Volume(vol.id)
                v.delete()
                print ('Deleted ' +vid)
                continue
            for tag in vol.tags:
                if tag['Key'] == 'Name':
                    value=tag['Value']
                    if value != 'DND' and vol.state=='available':
                        vid=vol.id
                        v=ec2.Volume(vol.id)
                        v.delete()
                        print ('Deleted ' +vid)

Or you can specify the list of Unused EBS Volumes that need to be deleted.

import boto3
ec2 = boto3.resource('ec2',region_name='eu-west-3')
volume_ids = ['vol-029af2107c0a0807d', ‘vol-029af2107c0a08123’]
def lambda_handler(event, context):
    for volid in volume_ids:
        vid=volid
        v=ec2.Volume(vid)
        v.delete()
        print ('Deleted ' +vid)

Save the function by clicking on the Save button.

Before we execute/test the code, we need to create an event. We shall create a simple event. To create an event, click on "Select a test event" - > Configure test event.

On the following screen, name the event and keep the event template as is and click on "Create".

Once the code and event is ready, the last thing which is left before we test or execute the function is to assign the required policies to the Lambda Function. To assign the required policy, scroll down and click on "View the delete-unused-ebs-volumes-role-ruemgr4x role" and open it in the new window.

Click on "Attach Policy" to attach the required policy to this IAM Role.

Search for EC2 and attach "AmazonEC2FullAccess'' policy. This policy will give full access to the Lambda Function on EC2 Instances.

Now, we are ready to execute the Function. Click on "Test".

Once you execute the function, you can see the logs in Execution Result.

You can confirm if the unused EBS Volume has/have been deleted or not by going to the main dashboard of EC2 instance.

Here, as you see the unused EBS Volume is no more available in the console which means it has been successfully deleted by the Lambda Function.

Conclusion

In this article, we saw how to write a Lambda Function to delete the Unused EBS Volumes. This can help us to save some extra cost on the AWS Account.

Share this page:

0 Comment(s)