Skip to content

Instantly share code, notes, and snippets.

@jayangshu84
Last active May 3, 2017 23:12
Show Gist options
  • Save jayangshu84/eda66aadd47e83f9dc2680b7c916a6db to your computer and use it in GitHub Desktop.
Save jayangshu84/eda66aadd47e83f9dc2680b7c916a6db to your computer and use it in GitHub Desktop.
Create EBS Snapshot - Lambda code (filter on running instances or with specific name tag)
import boto3
import datetime
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']}])
#If you want to filter on Instance Name
#Filters=[{'Name': 'tag:Name', 'Values': ['Keep Running']}])
for instance in instances:
instance_name = filter(lambda tag: tag['Key'] == 'Name', instance.tags)[0]['Value']
print("name: %s - id: %s" % (instance_name, instance.id))
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"))
print 'description: %s' % (description)
if volume.create_snapshot(VolumeId-volume.volume_id, Description=description):
print("Snapshot created with description [%s]" % description)
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