Created
April 12, 2017 00:14
-
-
Save jayangshu84/0bc2feae9b11a36806c3657d79546570 to your computer and use it in GitHub Desktop.
Create EBS Snapshot and Delete old scheduled snapshot - Lambda code {Number of days can be configured}
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 datetime | |
import pytz | |
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-%s' % (instance_name, volume.volume_id, | |
datetime.datetime.now().strftime("%Y%m%d-%H%M%S")) | |
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 = 15 | |
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]" % ( s.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