Delete unused EBS volumes through Lambda function
Tags: python, devops, aws, cloud
Published: 2023-12-31 12:10:36

Cleaning your AWS unused resources considered one of the issues that we face a lot, sometimes we forget a running EC2, unused EBS or ELB, which may lead to a high bill by end of the month.

in this article I made a solution by using some of AWS services to automate the deletion of unused EBS, the setup is based actually on EventBridge, Lambda function & SNS for notification.

We will cover the setup of the solution step by step in order to have your solution ready to use.


I have created two lambda functions, one of them to list the unused EBS in case if you don't want to take any action, just a list of these unused EBS, the other one will delete these EBS and will send you an email with the list of the deleted volumes, it's your choice to use any of them or both together.

1- We will start by creating a Lambda function by the below configuration


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4oakocs9c9c622xxk212.png)

for the service role we will create a role with the below policy to allow the Lambda function to access the EBS and SES, we will discuss the SES later and know why we are going to use.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ct35w4kirs8qw7d40b5n.png)

2- Now we are going to modify the code part for the lambda function, I have used the boto3 module

```
import boto3

def lambda_handler(event, context):
    ec2_client = boto3.client('ec2')
    ses_client = boto3.client('ses')
    
    unused_volumes = []
    CHARSET='UTF-8'
    
    volumes = ec2_client.describe_volumes()
    
    
    for volume in volumes['Volumes']:
        if len(volume['Attachments']) == 0:
            unused_volumes.append(volume['VolumeId'])
            print(unused_volumes)
            print("-------"*5)
    
    
    email_body = """
            <html>
                <head></head>
                <h1 style='text_aligned:center'>Unused Volumes in your account </h1>
                <p style='color:red'>below list contains the unused volumes </p>
            </html>
        """
    
    for vol in unused_volumes:
        email_body = email_body + "VolumeId {} \n".format(vol)
        
    print(email_body)
    
    for delete_vol in unused_volumes:
        response_delete = ec2_client.delete_volume(
                VolumeId=delete_vol,
                DryRun=False
        )
    
    print(response_delete)
    
    response = ses_client.send_email(
            Destination={
                "ToAddresses": ['x@example.com','y@example.com']
             },
            Message={
                "Body":{
                    "Html":{
                        "Charset":CHARSET,
                        "Data": email_body
                    }
                },
                "Subject":{
                        "Charset":CHARSET,
                        "Data": "This email address notify you with the unused volumes into your account"
                    }
                },
                Source = "x@example.com"
        )
```
simply the code will start looking use the describe volume function and will loop over the response to get the no attached volumes, then will be added to a list to have one list contains all the volumes, this list will be used later to be sent via email using AWS SES service

we have email body, and we will append the unused volume list to it.

3- Now we should use AWS SES to setup our destinations that going to send email notification, you should create identity to be verified as below 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dfeqxjqlbrgp1xe1fay7.png)

4- I have the below unused volume on my account, I'm using Cloud9 to test my code, we are going to run it through Cloud9.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sk7xm46o0pwhwcu5xr9w.png)


Cloud9 response after we run the code 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f0oeqlscdn9jbf3ag134.png)


the email that received from AWS SES should look like below:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikpdvajr1ypyqwpbu224.png)


5- Let's Automate this through AWS EventBridge, after uploading your Lambda function you need to add EventBridge As a trigger 



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kw2skint77gg41dld7j0.png)



Configure your rule with any configuration you want, I have configured for example a rule to run every 5 minutes, It means that every 5 minutes it will trigger our lambda function 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7x7ra8doau38juwlr3xe.png)

Now you have automated the deletion of the unused EBS volumes to save some money :).