Reach Us

CloudifyOps Mini-blog series: Streamlining Resource Management: Deleting Untagged Volume with AWS Lambda

Efficient resource management is crucial to maintaining a well-organized and cost-effective AWS environment. This guide outlines the process of streamlining resource management, specifically focusing on the automated deletion of untagged Elastic Block Store (EBS) volumes using AWS Lambda. By leveraging AWS CloudWatch events and Lambda functions, this solution ensures the automatic removal of untagged volumes, promoting a cleaner and more controlled infrastructure.

By following the steps below, you can create an AWS CloudWatch event rule and a Lambda function to enable the auto-delete solution of untagged volumes.

Workflow steps

  1. A user creates an EBS volume.
  2. A CloudWatch event rule monitors and is triggered upon the creation of the event.
  3. The CloudWatch event rule detects an applicable event and invokes a Lambda function to delete the untagged volumes.

Solution Setup

Step 1: Create and authorize the Lambda function to delete the untagged EBS volume.

  • Use the Lambda console to create a function. In a few minutes, you can create and deploy a function and test it in the console.
  • The auto-delete Lambda function used in this solution needs permission to interact with the AWS services on your behalf. Create an IAM permissions policy that allows the Lambda function to invoke the service action.

Step 2: Now configure a CloudWatch Event to use a cron expression to schedule a Lambda function when invoked.

  • Choose the Lambda function. Under Designer, choose Add trigger.
  • Set the trigger type to CloudWatch Events/EventBridge.
  • For Rule, choose Create a new rule.
  • Fill in the rule name and description.
  • For rule type, select Schedule expression.
  • In the Schedule expression field, enter a cron expression. For example, cron(0 12 ? MON-FRI ). Choose Add.

Step 3: Verify the auto-delete functionality.

Code and its summary

  1. For volumes that are in the ‘available’ state, it checks if the volume is untagged (i.e., it doesn’t have any tags) or if it doesn’t have a tag with the key ‘purpose’ and value ‘dnd’. If either condition is met, the volume ID is added to the untagged_or_non_dnd_volumes list.
  2. After identifying the untagged or non-‘dnd’ volumes, the code proceeds to delete them using ec2_client.delete_volume(). During the deletion process, it prints a message for each volume being deleted, including the volume ID.
  3. Finally, the code prints the list of volume IDs for the untagged or non-‘dnd’ volumes that were deleted. This script is useful for cleaning up EBS volumes that do not meet specific tagging criteria, which can help with cost management and resource organization in AWS.
import boto3

# Initialize AWS session and EC2 client
aws_access_key_id = ‘Enter your Access Key ID’
aws_secret_access_key = 'Enter your Secret Access Key’
region_name = 'us-east-2'  # Make sure to enclose the region name in quotes

# Replace with your AWS profile name or configure credentials
session = boto3.Session(
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
    region_name=region_name
)

ec2_client = session.client('ec2')

# Initialize an empty list to store untagged or non-'dnd' EBS volumes
untagged_or_non_dnd_volumes = []

# Step 1: List all EBS volumes
response = ec2_client.describe_volumes()

# Step 2: Iterate through volumes and check state and tags
for volume in response['Volumes']:
    # Check if the volume is in the 'available' state
    if volume['State'] == 'available':
        # Check if the volume is untagged or does not have the 'dnd' tag
        if 'Tags' not in volume or not any(tag['Key'] == 'purpose' and tag['Value'] == 'dnd' for tag in volume['Tags']):
            untagged_or_non_dnd_volumes.append(volume['VolumeId'])

# Step 3: Delete untagged or non-'dnd' EBS volumes
for volume_id in untagged_or_non_dnd_volumes:
    print(f"Deleting EBS volume {volume_id}")
    ec2_client.delete_volume(VolumeId=volume_id)

# Print the list of untagged or non-'dnd' volumes
print("Untagged or non-'dnd' EBS volumes:")
print(untagged_or_non_dnd_volumes)

To know more about how CloudifyOps, an AWS Advanced Consulting Partner, can help you optimize your cloud costs, write to us today at sales@cloudifyops.com.

Privacy Settings
We use cookies to enhance your experience while using our website. If you are using our Services via a browser you can restrict, block or remove cookies through your web browser settings. We also use content and scripts from third parties that may use tracking technologies. You can selectively provide your consent below to allow such third party embeds. For complete information about the cookies we use, data we collect and how we process them, please check our Privacy Policy
Youtube
Consent to display content from - Youtube
Vimeo
Consent to display content from - Vimeo
Google Maps
Consent to display content from - Google
Spotify
Consent to display content from - Spotify
Sound Cloud
Consent to display content from - Sound
Contact Us