Effortlessly Clean Up Unused EBS Volumes on AWS with a Lambda Function

Amazon Elastic Block Store (EBS) is a high-performance block storage service that functions as an external disk for EC2 Instances, allowing you to store data efficiently. If EBS Volumes remain unused and are still available in your account, AWS continues to charge for them, leading to unnecessary expenses. To optimize costs, we will explore creating a Lambda function to identify and delete such unused EBS Volumes.

Pre-requisites

  1. AWS Account (Create if you don’t have one).
  2. Basic understanding of EC2 Instances. Click here to learn more.
  3. Basic understanding of Lambda. Click here to learn more.

What will we do?

  1. Log in to AWS.
  2. Create a Lambda Function to delete unused EBS Volumes.

Log in to AWS

  1. Click here to access the AWS Login Page.

Upon hitting the above link, log in using your credentials to see the AWS main console with all listed services.

After logging in successfully, the main console displays all available AWS services.

Create a Lambda Function to Delete Unused EBS Volumes

Navigate to “Services” at the top left, search for “EC2” and access the EC2 dashboard.

On the EC2 dashboard, scroll down, and click “Volumes” under “Elastic Block Storage“.

Here, all EBS Volumes in the selected region appear. Volumes in the “available” state are unused and unattached to any EC2 Instances, making them safe to delete unless they contain important data.

While volumes can be deleted from this console, if there are hundreds or thousands of unused volumes, automation becomes useful.

To automate unused volume deletion, “Lambda Functions” are ideal. Click “Services” at the top left of the screen and search for “Lambda”.

On the Lambda dashboard, click “Create Function”.

Create a function from scratch. Name the function and select the Runtime. We’ll use a Python Runtime to automate the deletion process. Click “Create function” to proceed.

The screen with the sample function code will appear.

Replace the existing function code with the following code to delete unused EBS Volumes. For volumes marked “Name: DND”, the function won’t delete them.


      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)
    

Alternatively, specify the list of unused EBS Volumes 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 the Save button.

Before executing or testing the code, create a simple event. Click “Select a test event” -> “Configure test event”.

On the following screen, name the event, keep the event template as is, and click “Create”.

Before testing the function, assign the required policies to the Lambda Function. Scroll down, click “View the delete-unused-ebs-volumes-role role”, and open it in a new window.

Click “Attach Policy” to add the necessary policy to this IAM Role.

Search and attach “AmazonEC2FullAccess” policy to give full access to the Lambda Function on EC2 Instances.

Now, you’re ready to execute the function. Click “Test”.

Post-execution, logs are available in the Execution Result.

Confirm deletion of unused EBS Volumes on the EC2 dashboard.

If unused EBS Volumes are absent, the Lambda Function successfully deleted them.

Conclusion

This article covered how to write a Lambda Function to delete unused EBS Volumes, assisting in reducing extra AWS costs.

FAQs

  • What is Amazon EBS?Amazon Elastic Block Store (EBS) is a high-performance block storage service designed for use with Amazon EC2 for both throughput and transaction-intensive workloads.
  • Why automate the deletion of unused EBS Volumes?Automation helps manage larger numbers of resources effectively, reducing time and manual effort while minimizing costs due to unused storage.
  • What is a Lambda function?A Lambda function is a serverless compute service that lets you run code in response to events and automatically manages the underlying compute resources.
  • Can I stop specific volumes from being deleted?Yes, by tagging volumes with “Name: DND”, they are excluded from automatic deletion by the Lambda function.