Delete unused EBS volumes through Lambda function

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

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.

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"
)
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"
        )
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" )

Enter fullscreen mode Exit fullscreen mode

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

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.

Cloud9 response after we run the code

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

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

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

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

原文链接:Delete unused EBS volumes through Lambda function

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
Forever facing sunlight, so you can not see the shadow of the.
永远面向阳光,这样你就看不见阴影了
评论 抢沙发

请登录后发表评论

    暂无评论内容