Created
June 12, 2018 21:53
-
-
Save heyseus1/9c37727580a7b215ac91fd6b656953ac to your computer and use it in GitHub Desktop.
EBS Backup script
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
#!/usr/bin/python2.7 | |
import boto3 | |
import datetime | |
import pytz | |
import os | |
ec2 = boto3.resource('ec2') | |
def lambda_handler(event, context): | |
print("\n\nAWS snapshot backups starting at %s" % datetime.datetime.now()) | |
instances = ec2.instances.filter( | |
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) | |
for instance in instances: | |
instance_name = filter(lambda tag: tag['Key'] == 'Name', instance.tags)[0]['Value'] | |
for volume in ec2.volumes.filter(Filters=[{'Name': 'attachment.instance-id', 'Values': [instance.id]}]): | |
description = 'scheduled-%s-%s' % (instance_name, | |
datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")) | |
if volume.create_snapshot(VolumeId=volume.volume_id, Description=description): | |
print("Snapshot created with description [%s]" % description) | |
for snapshot in volume.snapshots.all(): | |
retention_days = int(os.environ['retention_days']) | |
if snapshot.description.startswith('scheduled-') and ( datetime.datetime.now().replace(tzinfo=None) - snapshot.start_time.replace(tzinfo=None) ) > datetime.timedelta(days=retention_days): | |
print("\t\tDeleting snapshot [%s - %s]" % ( snapshot.snapshot_id, snapshot.description )) | |
snapshot.delete() | |
print("\n\nAWS snapshot backups completed at %s" % datetime.datetime.now()) | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment