Last active
March 4, 2016 05:40
-
-
Save jerm/fcac6f8b07ffff52e4b5 to your computer and use it in GitHub Desktop.
Easy way to snap all volumes on an instance.
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 boto | |
import datetime | |
def lookup_instance_by_id(instance_id): | |
conn = boto.connect_ec2() | |
try: | |
instance = conn.get_all_instances(filters = {'instance_id':instance_id})[0].instances[0] | |
except IndexError: | |
return False | |
if instance.state != 'terminated': | |
return instance | |
else: | |
debug("Instance %s is terminated" % instance_id) | |
return False | |
def snap_instance_volumes(instance=None, expire_hours=0, expire_days=0, expire_weeks=1): | |
""" Takes instance id __OR__ instance object | |
creates dated and labeled snapshots of all an instance's attached volumes | |
snaps set to expire after 1 week (clean-up by expiration process that needs to | |
be run regularly)""" | |
expire_hours = int(expire_hours) + (int(expire_days) * 24 ) + (int(expire_weeks) * 7 * 24) | |
conn = boto.connect_ec2() | |
try: | |
__foo = instance.id | |
except AttributeError: | |
lookedup_instance = lookup_instance_by_id(instance) | |
if lookedup_instance is False: | |
print "No Such instance %s" % instance | |
return False | |
else: | |
instance = lookedup_instance | |
timestamp = datetime.datetime.now() | |
expire_datetime = timestamp + datetime.timedelta(hours=expire_hours) | |
snaps = [] | |
for attach_point,bdm in instance.block_device_mapping.iteritems(): | |
try: | |
instance_name = instance.tags['Name'] | |
except KeyError: | |
instance_name = instance.id | |
volume = conn.get_all_volumes(filters={"volume_id":bdm.volume_id})[0] | |
description = "%s^%s^%s" % (instance.id, instance_name, timestamp) | |
snapshot = volume.create_snapshot(description) | |
print snapshot, volume.attach_data.device, description | |
conn.create_tags([snapshot.id], { | |
'Name': "%s %s" % (instance_name, volume.attach_data.device), | |
'device': volume.attach_data.device, | |
'datetime': timestamp, | |
'instance_id': instance.id, | |
'expire': expire_datetime, | |
'image_id': instance.image_id, | |
}) | |
snaps.append(snapshot) | |
return snaps |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment