Skip to content

Instantly share code, notes, and snippets.

@jonathan-kosgei
Created April 19, 2017 03:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathan-kosgei/df56ce5021270c4bf193c24196b80f42 to your computer and use it in GitHub Desktop.
Save jonathan-kosgei/df56ce5021270c4bf193c24196b80f42 to your computer and use it in GitHub Desktop.
AWS Lambda backup EBS volumes with BOTO3
# Scheduling the above script hourly. Ensure you're properly authenticated via aws configure.
#!/bin/bash
zip ebs-backup-worker.zip .schedule-ebs-snapshot-backups.py
aws lambda create-function --function-name ebs-backup-worker \
--runtime python2.7 \
--role "arn for your lambda user's role" \
--handler lambda_handler \
--zip-file fileb:///ebs-backup-worker.zip
aws events put-rule \
--name ebs-hourly-snapshot-rule \
--schedule-expression 'rate(1 hour)'
aws lambda add-permission \
--function-name ebs-backup-worker \
--statement-id ebs-hourly-snapshot \
--action 'lambda:InvokeFunction' \
--principal events.amazonaws.com \
--source-arn arn:aws:events:${var.region}:${var.account_id}:rule/ebs-hourly-snapshot-rule
aws events put-targets --rule ebs-hourly-snapshot-rule --targets file://targets.json
# targets.json below
""" Make sure to create the "backup" tag on the volumes you want to backup.
For authentication, setup the aws policy and user as specified in the snapshot-trust.json and snapshot-policy.json
Inspired by: https://serverlesscode.com/post/lambda-schedule-ebs-snapshot-backups/
"""
from time import gmtime, strftime
import boto3
region = "us-west-2"
backup_tag = "backup"
client = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
volumes = client.describe_volumes(Filters=[{"Name":"tag-key", "Values":[backup_tag]}])
for volume in volumes["Volumes"]:
time = strftime("%a, %d %b %Y %X +0000", gmtime())
snapshot = ec2.create_snapshot(VolumeId=volume["VolumeId"], Description='EBS Backup {0}'.format(time))
print "Created : {0} ID: {1}".format(snapshot.description, snapshot.snapshot_id)
[
{ "Id": "1",
"Arn": "arn:aws:lambda:${var.region}:${var.account_id}:function:ebs-backup-worker"
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment