Skip to content

Instantly share code, notes, and snippets.

@davebarnwell
Last active November 22, 2023 09:44
Show Gist options
  • Save davebarnwell/dd2c82f61650f209e5ecb8e505f4774c to your computer and use it in GitHub Desktop.
Save davebarnwell/dd2c82f61650f209e5ecb8e505f4774c to your computer and use it in GitHub Desktop.
AWS EC2 automated snapshot backup using Python script called from AWS lambda

AWS automated backups of AWS EC2 instances using AWS lambda.

Create a Python-based AWS lambda script like aws_ec2_snapshot.py

Configure an event source so that it runs daily thus giving you a reliable automated EC2 backup solution which has no other dependacies, although you'll need to manage cleaning down old backups, which is an obvious extra to add to the script, as is using the SES API to send email confirmations.

The Lambda will need to have appropriate privileges under IAM see iam.json example

import boto3
BACKUP_VOLUMES = [
'vol-xxxxxxxx'
]
def lambda_handler(event, context):
ec2 = boto3.resource('ec2')
for volume in BACKUP_VOLUMES:
ec2.create_snapshot(VolumeId=volume, Description='Automated backup')
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"ec2:CreateSnapshot",
"ec2:DeleteSnapshot",
"ec2:DescribeSnapshots"
],
"Resource": "*"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment