Maximize Your AWS Savings: Automate Snapshot Cleanup on AMI Deregistration

Listen to this Post

Featured Image
When you deregister an Amazon Machine Image (AMI), the associated Elastic Block Store (EBS) snapshots are not automatically deleted. These lingering snapshots can accumulate costs over time. Automating their cleanup using AWS EventBridge and Lambda ensures cost efficiency.

You Should Know:

1. Understanding AMI and Snapshot Retention

  • AMI: A template for EC2 instances, including OS and configurations.
  • EBS Snapshots: Created when an AMI is generated but persist after AMI deregistration.

2. Automating Cleanup with AWS EventBridge and Lambda

Follow these steps to automate snapshot deletion:

Step 1: Create an IAM Role for Lambda

aws iam create-role --role-name LambdaAMICleanupRole --assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "lambda.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}'

Step 2: Attach Required Permissions

aws iam attach-role-policy --role-name LambdaAMICleanupRole --policy-arn arn:aws:iam::aws:policy/AmazonEC2FullAccess
aws iam attach-role-policy --role-name LambdaAMICleanupRole --policy-arn arn:aws:iam::aws:policy/CloudWatchLogsFullAccess

Step 3: Deploy the Lambda Function

Use Python (`boto3`) to delete snapshots:

import boto3

def lambda_handler(event, context):
ec2 = boto3.client('ec2')
ami_id = event['detail']['requestParameters']['imageId']

Get snapshots associated with the deregistered AMI
snapshots = ec2.describe_images(ImageIds=[bash])['Images'][bash]['BlockDeviceMappings']
for snapshot in snapshots:
if 'Ebs' in snapshot:
snapshot_id = snapshot['Ebs']['SnapshotId']
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted snapshot: {snapshot_id}")

Step 4: Set Up EventBridge Rule

Configure EventBridge to trigger Lambda on AMI deregistration:

aws events put-rule --name AMIDeregistrationRule --event-pattern '{
"source": ["aws.ec2"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventSource": ["ec2.amazonaws.com"],
"eventName": ["DeregisterImage"]
}
}'

Step 5: Add Lambda as Target

aws events put-targets --rule AMIDeregistrationRule --targets 'Id=1,Arn=YOUR_LAMBDA_ARN'

3. Verify the Automation

Test by deregistering an AMI and checking CloudWatch Logs:

aws ec2 deregister-image --image-id ami-1234567890

What Undercode Say

Automating AWS resource cleanup prevents unnecessary costs. This method applies to:
– Unattached EBS Volumes (aws ec2 delete-volume --volume-id vol-12345)
– Old Lambda Logs (aws logs delete-log-group --log-group-name /aws/lambda/old-function)
– Stale CloudFormation Stacks (aws cloudformation delete-stack --stack-name old-stack)

Expected Output:

  • Snapshots deleted automatically upon AMI deregistration.
  • Reduced AWS costs with minimal manual intervention.

Prediction

As cloud costs rise, more organizations will adopt automated cleanup strategies, integrating AI-driven cost optimization tools like AWS Cost Explorer and third-party solutions.

Reference:

IT/Security Reporter URL:

Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram