Last active
February 2, 2016 08:36
-
-
Save ryansb/08c264d0d17bf672bb55 to your computer and use it in GitHub Desktop.
This file contains hidden or 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') | |
def lambda_handler(event, context): | |
reservations = ec.describe_instances().get( | |
'Reservations', [] | |
) | |
instances = sum( | |
[ | |
[i for i in r['Instances']] | |
for r in reservations | |
], []) | |
instances = [i for i in instances if 'NoBackup' not in [t.get('Key') for t in i['Tags']]] | |
print "Found %d instances that need backing up" % len(instances) | |
to_tag = collections.defaultdict(list) | |
for instance in instances: | |
try: | |
retention_days = [ | |
int(t.get('Value')) for t in instance['Tags'] | |
if t['Key'] == 'Retention'][0] | |
except IndexError: | |
retention_days = 7 | |
for dev in instance['BlockDeviceMappings']: | |
if dev.get('Ebs', None) is None: | |
continue | |
vol_id = dev['Ebs']['VolumeId'] | |
print "Found EBS volume %s on instance %s" % ( | |
vol_id, instance['InstanceId']) | |
snap = ec.create_snapshot( | |
VolumeId=vol_id, | |
) | |
try: | |
instance_name = [ | |
t.get('Value') for t in instance['Tags'] | |
if t['Key'] == 'Name'][0] | |
except IndexError: | |
instance_name = 'unknown' | |
ec.create_tags( | |
Resources=[snap['SnapshotId']], | |
Tags=[{'Key': 'ParentInstance', 'Value': instance['InstanceId']}, | |
{'Key': 'ParentInstanceName', 'Value': instance_name}, | |
{'Key': 'MountPoint', 'Value': dev['DeviceName']}] | |
) | |
to_tag[retention_days].append(snap['SnapshotId']) | |
print "Retaining snapshot %s of volume %s from instance %s for %d days" % ( | |
snap['SnapshotId'], | |
vol_id, | |
instance['InstanceId'], | |
retention_days, | |
) | |
for retention_days in to_tag.keys(): | |
delete_date = datetime.date.today() + datetime.timedelta(days=retention_days) | |
delete_fmt = delete_date.strftime('%Y-%m-%d') | |
print "Will delete %d snapshots on %s" % (len(to_tag[retention_days]), delete_fmt) | |
ec.create_tags( | |
Resources=to_tag[retention_days], | |
Tags=[ | |
{'Key': 'DeleteOn', 'Value': delete_fmt}, | |
] | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment