Simple AWS Lambda Function to Snapshot All Attached EBS Volumes on an EC2 Instance

Automating EBS snapshots is a critical part of maintaining a resilient infrastructure. Below is a simple Python Lambda function that identifies all volumes attached to an EC2 instance and creates a snapshot for each.

Modern Update (2026): While custom Lambda scripts like this one are great for specific logic, AWS now recommends using Amazon Data Lifecycle Manager (DLM) for standardized snapshot automation. It is policy-driven and doesn't require maintaining custom code.

Lambda Function (Python)

import boto3
import datetime

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    # Replace with your Instance ID or logic to fetch it
    instance_id = 'i-xxxxxxx' 
    
    descriptions = ec2.describe_instances(InstanceIds=[instance_id])
    for reservation in descriptions['Reservations']:
        for instance in reservation['Instances']:
            for block_device in instance['BlockDeviceMappings']:
                vol_id = block_device['EBS']['VolumeId']
                description = f"Automated snapshot of {vol_id} from {instance_id} at {datetime.datetime.now()}"
                
                snapshot = ec2.create_snapshot(VolumeId=vol_id, Description=description)
                print(description)
                
    return "Finished automated snapshot of all attached volumes."

Required IAM Policy Document

Attach this policy to your Lambda Execution Role. Be sure to replace <***BUCKET NAME***> if your script interacts with S3 for logging or configuration.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "ec2:CreateSnapshot",
        "ec2:DescribeInstances"
      ],
      "Resource": "*"
    }
  ]
}

AWS Policy Generator is a helpful tool if you want to further restrict these permissions.


NOTICE: All thoughts/statements in this article are mine alone and do not represent those of Amazon or Amazon Web Services. Referenced AWS services are the property of AWS. While I strive for accuracy, I disclaim liability for any disruption caused by errors or omissions.