Skip to main content

Command Palette

Search for a command to run...

Day - 16 | AWS Cloud Cost Optimization

Published
3 min readView as Markdown

AWS Cloud Cost Optimization – Identifying Stale EBS Snapshots with Lambda

Cost optimization is one of the core pillars of AWS best practices, especially when running large or long-lived cloud environments. In this post, I’ll walk through a simple but powerful AWS solution that helps reduce unnecessary storage costs by identifying and deleting stale EBS snapshots — a common cost sink in many AWS accounts

💡 What Are EBS Snapshots?

EBS Snapshots are point-in-time backups of your Amazon Elastic Block Store (EBS) volumes. They are stored in Amazon S3 and billed based on consumed space. Snapshots are valuable for recovery and backup strategies, but old or unused snapshots can accumulate and cost money over time.

🚀 The Goal

This project aims to:

  • Scan all EBS snapshots in your AWS account

  • Determine which snapshots are not associated with any active EC2 instance

  • Delete those stale snapshots automatically
    This helps eliminate storage waste and reduces monthly AWS bill.

🧠 How It Works – Lambda + Boto3

The core of the solution is an AWS Lambda function written in Python that:

  1. Lists all EBS snapshots owned by the account

  2. Lists all EC2 instances (running or stopped)

  3. Checks if each snapshot belongs to a volume attached to any active instance

  4. Deletes snapshots that are no longer associated with any instance

This logic runs in a serverless manner and can be scheduled via CloudWatch Events (EventBridge).

🧪 Python Lambda Code (Excerpt)

Below is the key script used in Day 18:

import boto3

ec2 = boto3.client("ec2")

def lambda_handler(event, context):
    snapshots = ec2.describe_snapshots(OwnerIds=["self"])["Snapshots"]
    instances = ec2.describe_instances(Filters=[{"Name": "instance-state-name", "Values": ["running", "stopped"]}])["Reservations"]

    instance_volumes = []
    for reservation in instances:
        for instance in reservation["Instances"]:
            for mapping in instance.get("BlockDeviceMappings", []):
                instance_volumes.append(mapping["Ebs"]["VolumeId"])

    for snapshot in snapshots:
        volume_id = snapshot.get("VolumeId")
        if volume_id not in instance_volumes:
            print(f"Deleting stale snapshot {snapshot['SnapshotId']} for volume {volume_id}")
            ec2.delete_snapshot(SnapshotId=snapshot["SnapshotId"])

This script uses Boto3 (AWS SDK for Python) to interact with EC2 resources and manage snapshots programmatically

📅 Scheduling the Clean-Up

To run this cost optimization task automatically:

  1. Create a Lambda function in AWS Console

  2. Deploy the Python script above

  3. Configure necessary IAM permissions to describe and delete EBS snapshots

  4. Create a CloudWatch Event Rule (EventBridge) to trigger the Lambda periodically (e.g., daily or weekly)

🔐 Security Note (IAM Permissions)

Make sure the IAM role used by the Lambda function has permissions like:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Effect":"Allow",
      "Action":[
        "ec2:DescribeSnapshots",
        "ec2:DescribeInstances",
        "ec2:DeleteSnapshot"
      ],
      "Resource":"*"
    }
  ]
}

📊 Why This Matters

  • Unattached snapshots continue to accumulate cost even if the associated instance is terminated.

  • Automating cleanup reduces manual effort, ensures cost-efficiency, and prevents bills from growing unnoticed.

  • Combining Lambda with scheduled events exemplifies how AWS serverless services can solve real cloud management challenges.

More from this blog

Bipul Kumar

45 posts