Recently, we faced a situation where we found an account with over 25 TB of EBS snapshots, some of which dated back to 2017. These old snapshots had been piling up, creating substantial, unnecessary costs. We realized that without cleanup, costs would only increase, especially in our dev environment, where frequent changes to snapshots were generating excess storage overhead. This Lambda function was developed as a solution to automate the cleanup of outdated snapshots and refine our volume snapshot policy, allowing us to regain control over storage costs effectively.
1. Cost Management and Optimization
- Accruing Storage Costs: Each EBS snapshot incurs storage costs based on the amount of data stored. Over time, as snapshots accumulate, these costs can become significant, especially for organizations with multiple environments or large volumes of data.
- Automated Cleanup: A Lambda function helps to automate the deletion of older, unnecessary snapshots, ensuring that only the most recent backups are retained, which optimizes storage costs by freeing up space occupied by outdated snapshots.
2. Improved Operational Efficiency
- Avoid Manual Intervention: Managing snapshots manually can be time-consuming, especially in large-scale environments where multiple snapshots are created daily. By automating snapshot cleanup, the Lambda function eliminates the need for manual review and deletion, saving valuable time for the operations team.
- Consistency and Reliability: Automation ensures that snapshots are managed consistently according to defined policies. This prevents oversight and ensures a reliable, predictable process for snapshot lifecycle management.
3. Risk Mitigation
- Avoid Accidental Deletion of Important Snapshots: By automating with a well-defined Lambda function, you can set policies to retain only the latest snapshots, significantly reducing the risk of accidentally deleting snapshots that are crucial for disaster recovery or compliance.
- Streamlined Backup Management: With snapshots cleaned up regularly, only relevant backups are kept, simplifying recovery processes. This means that if data needs to be restored, engineers don’t need to sift through an excess of snapshots to locate the right one, which is especially critical during high-pressure situations like system recovery.
4. Scalability
- Handles Growing Data Volumes: As infrastructure scales, so do the number of snapshots created. A Lambda function can automatically scale to handle snapshot cleanup across all regions and accounts without requiring additional infrastructure.
- Facilitates Cross-Region and Multi-Account Management: For enterprises with complex, multi-region, or multi-account setups, a Lambda function can centralize snapshot cleanup policies across environments, streamlining overall backup management.
5. Compliance and Audit Readiness
- Retention Policies: Many organizations must comply with data retention policies that dictate how long certain data must be kept. A Lambda function can enforce these retention rules consistently, ensuring snapshots are kept or deleted according to compliance requirements.
- Audit-Friendly: The function can be configured to generate a report of deleted snapshots and the remaining storage, making it easy to demonstrate compliance and cost efficiency during audits.
6. Enhanced Security
- Reduce Attack Surface: Unnecessary snapshots can potentially expose outdated or unpatched data. By regularly deleting unused snapshots, you reduce the attack surface, helping to protect sensitive information that may be stored in older snapshots.
- Automated Logs and Notifications: This function can log and notify when snapshots are deleted, offering visibility into backup and cleanup processes, which can be monitored to ensure secure and compliant operations.
Overview
This AWS Lambda function is designed to manage Amazon Elastic Block Store (EBS) snapshots by identifying old snapshots, optionally deleting them, storing a summary of the old snapshots in an Amazon S3 bucket, and notifying a specified Slack channel about the results. This function is especially useful for managing snapshot storage costs by ensuring that only the latest snapshots are retained while tracking the total space occupied by old snapshots.
Key Components
Logging Configuration: Configures logging for information and error handling.
Constants:
DELETE_SNAPSHOTS
: Enables or disables the deletion of old snapshots.SEND_SLACK_MESSAGE
: Controls whether a Slack notification will be sent.S3_BUCKET
andS3_KEY
: Define the S3 bucket and file name where the CSV report of old snapshots will be saved.SLACK_WEBHOOK_URL
andSLACK_CHANNEL
: Specify the Slack Webhook URL and the Slack channel to send a notification about the uploaded report.
Dependencies: Uses the
boto3
library to interact with AWS services,csv
for generating CSV output, andurllib3
for HTTP requests (to send Slack notifications).
Function Details
lambda_handler(event, context)
This is the main function that runs when the Lambda function is triggered. It performs several steps:
Retrieve EBS Snapshots:
- Uses the
describe_snapshots
API to get all EBS snapshots owned by the account, organized by volume. - Sorts the snapshots for each volume by the creation time (
StartTime
), from the most recent to the oldest.
- Uses the
Organize and Filter Snapshots:
- Groups snapshots by volume and retains only the newest 4 snapshots for each volume.
- Flags the older snapshots as candidates for deletion or reporting.
Generate CSV Report:
- Creates a CSV file in memory using
StringIO
, which will hold details of each old snapshot, including:SnapshotId
,StartTime
,VolumeId
,State
,Description
,Size (GiB)
, andName
.
- Accumulates and logs the total storage size (in GiB) occupied by the snapshots for each volume and overall.
- Creates a CSV file in memory using
Optional Deletion of Snapshots:
- If
DELETE_SNAPSHOTS
is enabled, the function deletes each identified old snapshot. - Logs each deletion action.
- If
Upload CSV to S3:
- The CSV report is uploaded to the specified S3 bucket and key, which provides a historical record of old snapshots and their associated storage costs.
Slack Notification:
- If
SEND_SLACK_MESSAGE
is enabled, the function sends a notification to the specified Slack channel with a link to the S3 report and the total storage size marked for deletion.
- If
Error Handling:
- Uses
try-except
blocks to handle and log any errors encountered during the snapshot processing, deletion, or Slack notification stages.
- Uses
Helper Function: get_instance_name(ec2, volume_id)
This function retrieves the name of an EC2 instance attached to a given volume ID:
- Uses the
describe_volumes
anddescribe_instances
APIs to fetch the instance associated with the specified volume. - Searches the instance tags to find and return the
Name
tag value.
Sample Output and Notifications
- CSV Output: The CSV contains details about old snapshots by volume, with information about each snapshot’s size and other metadata. A total size summary is also added to the CSV.
- Slack Notification: Sends a message to the specified Slack channel with details about the report location in S3 and the total size (in GiB) of snapshots targeted for deletion.
Configuration Tips
- S3 Bucket and Slack Channel: Update
S3_BUCKET
,S3_KEY
,SLACK_WEBHOOK_URL
, andSLACK_CHANNEL
as per your environment. - Permissions: Ensure the Lambda function’s IAM role has permissions to access EC2 (for snapshots), S3 (for uploading CSV files), and the necessary logging and notification services.
IAM Role policies
1. EC2 Permissions (for managing snapshots)
{"Version": "2012-10-17","Statement": [{"Effect": "Allow","Action": ["ec2:DescribeSnapshots","ec2:DeleteSnapshot","ec2:DescribeVolumes","ec2:DescribeInstances"],"Resource": "*"}]}
2. S3 Permissions (for uploading the CSV report)
{"Version": "2012-10-17","Statement": [{"Effect": "Allow","Action": ["s3:PutObject","s3:GetObject"],"Resource": "arn:aws:s3:::verato-snapshot-inspection/*" // Replace with your bucket name}]}
3. CloudWatch Logs Permissions (for logging)
{"Version": "2012-10-17","Statement": [{"Effect": "Allow","Action": ["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource": "*"}]}