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.

Author’s Note: This article reflects my personal professional experience and opinions. While my insights are informed by my professional history, these views are my own and do not represent the official position of my former employer.

About the Author: Jacob Marks is an engineering leader with over 20 years of experience, including a decade at Amazon Web Services (AWS) where he led teams in EC2 Core Platform and the development of the AWS Payment Cryptography service.

Labels

.NET .NET 10 .NET 3.5 Active Directory AD DS Adoption AI AI coding AI Ethics AI Hype Alerts Amazon Cognito Amazon DLM Amazon Q Anthropic AppDomain Architecture Artificial Intelligence Asia Pacific Sydney ASP.net ASPxGridView Audit Readiness Auto Recovery Automation AWS AWS Certified AWS Lambda AWS Payment Cryptography AWS SDK AWS Security Specialty Azure Azure DevOps Server Backup BIG-IP C# Career Growth Cartes Bancaires CB Certificate Bundle Certification Claude Cloud Cloud Certification Cloud Hosting Cloud Security CloudWatch CLR Content Query Cost Optimization Credentials CyberChef Database Defense Industry Deloitte Developer Tools Developers DevEx DevExpress DevOps DISA Disk Space DISM Distributed Systems DoD DoD CC SRG DUKPT EBS EC2 Engineering Engineering Leadership Engineering Management EnPasFltV2 Enterprise Event Receiver Exam F5 Federal IT FedRAMP Fintech FISMA GAC Generative AI GitHub gMSA GovCloud Government Compliance GridView Hardware Security Modules HSM IAM Identity Management IIS Infra Infrastructure as Code IT Tools Jacob Marks JavaScript jQuery Lambda Leadership Linqpad LLM lsass.exe LTM Memory Optimization Mentorship Microsoft Migration Multi-Region Keys NACL Native AOT Network Architecture Networking NIST ODBC Open Source Payment Cryptography Payments PCI Compliance Performance Platform Platform Architecture Power Tools PowerShell Python re:Invent Reachability Analyzer Redshift Relationships List Replace Root Volume SAA-C00 SAP-C00 Security Security Group Serverless SES SharePoint SharePoint 2010 Site Reliability SMTP Snapshot Software Engineering Solutions Architect Solutions Architect Professional SP 2007 SPAWAR SSL STIG Storage Strategy Sydney SysAdmin Team Foundation Server Team Utilities Tech Industry Technical Depth Technology TFS Tools Troubleshooting Upgrade Visual Studio VPC VPC Flow Logs Web Development WebPart WinDirStat Windows Server Windows Server 2025 WinForms