Last active
December 7, 2016 07:05
-
-
Save bdpdx/b9adb10b00aeb464c61664f491fb95e3 to your computer and use it in GitHub Desktop.
Amazon AWS EC2 Snapshot Creation Lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import collections | |
import datetime | |
ec = boto3.client('ec2') | |
# inspired by https://serverlesscode.com/post/lambda-schedule-ebs-snapshot-backups/ | |
# | |
# snapshot creation lambda | |
# this function creates snapshots | |
# prerequisites: | |
# only attached volumes are considered | |
# the instance that owns the volume must have a Backup=true tag | |
# individual volumes will be skipped if they have a Backup=false tag | |
def lambda_handler(event, context): | |
reservations = ec.describe_instances()['Reservations'] | |
for reservation in reservations: | |
for instance in reservation['Instances']: | |
backup = False | |
for tag in instance['Tags']: | |
key = tag['Key'] | |
value = tag['Value'] | |
if key == 'Backup': | |
backup = tag['Value'] == 'true' | |
break | |
if not backup: continue | |
for device in instance['BlockDeviceMappings']: | |
if device.get('Ebs', None) is None: continue | |
volumeId = device['Ebs']['VolumeId'] | |
info = ec.describe_volumes(VolumeIds=[volumeId])['Volumes'][0] | |
name = volumeId | |
skip = False | |
for tag in info['Tags']: | |
key = tag['Key'] | |
if key == 'Backup': | |
skip = tag['Value'] == 'false' | |
elif key == 'Name': | |
name += ' (' + tag['Value'] + ')' | |
if skip: | |
print 'Snapshot of volume %s skipped due to presence of Backup=false tag' % (name) | |
continue | |
print 'Snapshot of volume %s created' % (name) | |
snapshot = ec.create_snapshot(VolumeId=volumeId) | |
snapshotId = snapshot['SnapshotId'] | |
tags = [ | |
{'Key': 'createdByEBSSnapshotter', 'Value': 'true'}, | |
{'Key': 'Name', 'Value': name} | |
] | |
ec.create_tags(Resources=[snapshotId], Tags=tags) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment