Listen to this Post
Ensuring you waste as little money as possible on AWS resources should be a top priority. There are many cases where small charges can add up quickly. An example below shows how to use automation and events to deal with snapshot cleanup on AMI deregistration.
Amazon Machine Images (AMIs) are templates to launch an EC2 instances including the OS and other config. Snapshots for EBS volumes attached to an EC2 are created when an AMI is created from an EC2. These snapshots are then associated with the AMI. The issue is that these snapshots do not get deleted when you delete (deregister) the AMI. The charges for these are typically pretty small but they can add up over time and keeping them isn’t really useful.
Using services like Eventbridge is a perfect fit for many automation tasks. Since you can setup a rule in Eventbridge to watch for any action (like an AMI being deregistered), you can take care of associated cleanup based on the events.
Below, Vikas Arora shows how to do this using a call to a Lambda function when the events are seen.
Code Example: Automating Snapshot Cleanup with AWS Lambda and EventBridge
1. Create an EventBridge Rule:
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\"]}}" --state ENABLED
2. Create a Lambda Function:
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
ami_id = event['detail']['responseElements']['imageId']
<h1>Describe snapshots associated with the AMI</h1>
snapshots = ec2.describe_snapshots(Filters=[{'Name': 'description', 'Values': [f'<em>{ami_id}</em>']}])['Snapshots']
<h1>Delete snapshots</h1>
for snapshot in snapshots:
ec2.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
return {
'statusCode': 200,
'body': f"Snapshots for AMI {ami_id} have been deleted."
}
3. Add Permissions to Lambda Function:
aws lambda add-permission --function-name "SnapshotCleanupLambda" --statement-id "EventBridgeInvoke" --action "lambda:InvokeFunction" --principal "events.amazonaws.com" --source-arn "arn:aws:events:us-east-1:123456789012:rule/AMIDeregistrationRule"
4. Link EventBridge Rule to Lambda:
aws events put-targets --rule "AMIDeregistrationRule" --targets "Id"="1","Arn"="arn:aws:lambda:us-east-1:123456789012:function:SnapshotCleanupLambda"
What Undercode Say
In the realm of cloud computing, efficiency and cost management are paramount. The article highlights a common issue in AWS where snapshots associated with deregistered AMIs continue to incur costs. By leveraging AWS EventBridge and Lambda, we can automate the cleanup process, ensuring that these snapshots are deleted promptly, thus saving on unnecessary expenses.
The provided code demonstrates how to set up an EventBridge rule to trigger a Lambda function whenever an AMI is deregistered. The Lambda function then identifies and deletes the associated snapshots. This automation not only reduces manual intervention but also ensures that your AWS environment remains cost-effective.
To further enhance your AWS cost management, consider the following additional commands and practices:
- Monitor EC2 Instances:
aws ec2 describe-instances --query 'Reservations[<em>].Instances[</em>].[InstanceId,State.Name,InstanceType]' --output table
-
List Unattached EBS Volumes:
aws ec2 describe-volumes --filters Name=status,Values=available --query 'Volumes[*].VolumeId' --output text
-
Delete Unattached EBS Volumes:
for volume in $(aws ec2 describe-volumes --filters Name=status,Values=available --query 'Volumes[*].VolumeId' --output text); do aws ec2 delete-volume --volume-id $volume; done
-
Check S3 Bucket Sizes:
aws s3api list-buckets --query 'Buckets[*].Name' --output text | xargs -I {} aws s3 ls s3://{} --recursive --human-readable --summarize -
Set Up Billing Alarms:
aws cloudwatch put-metric-alarm --alarm-name "MonthlyBillingAlarm" --metric-name "EstimatedCharges" --namespace "AWS/Billing" --statistic "Maximum" --period 21600 --evaluation-periods 1 --threshold 100 --comparison-operator "GreaterThanOrEqualToThreshold" --dimensions Name=Currency,Value=USD --alarm-actions "arn:aws:sns:us-east-1:123456789012:BillingAlarmTopic"
By implementing these practices, you can ensure that your AWS environment is not only cost-efficient but also optimized for performance. The integration of automation tools like EventBridge and Lambda can significantly reduce the overhead associated with manual resource management, allowing you to focus on more strategic tasks.
For more detailed insights and advanced configurations, refer to the AWS Documentation. Additionally, exploring AWS Cost Explorer and AWS Budgets can provide further granularity in managing and forecasting your cloud expenses.
In conclusion, the combination of AWS services and automation scripts offers a robust solution for managing cloud resources effectively. By adopting these practices, you can minimize costs, enhance operational efficiency, and maintain a streamlined cloud environment.
References:
initially reported by: https://www.linkedin.com/posts/darryl-ruggles_maximize-your-aws-savings-automate-snapshot-activity-7301390721402425345-un1_ – Hackers Feeds
Extra Hub:
Undercode AI


