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.
Step 1: Create and authorize the Lambda function to delete the untagged EBS volume.
Step 2: Now configure a CloudWatch Event to use a cron expression to schedule a Lambda function when invoked.
Step 3: Verify the auto-delete functionality.
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.
CloudifyOps Pvt Ltd, Ground Floor, Block C, DSR Techno Cube, Survey No.68, Varthur Rd, Thubarahalli, Bengaluru, Karnataka 560037
Indiqube Vantage, 3rd Phase, No.1, OMR Service Road, Santhosh Nagar, Kandhanchavadi, Perungudi, Chennai, Tamil Nadu 600096.
CloudifyOps Inc.,
200, Continental Dr Suite 401,
Newark, Delaware 19713,
United States of America
Copyright 2024 CloudifyOps. All Rights Reserved