Skip to content

Instantly share code, notes, and snippets.

@hkarasek
Created October 22, 2015 07:26
Show Gist options
  • Save hkarasek/711d59864a83fdc0e505 to your computer and use it in GitHub Desktop.
Save hkarasek/711d59864a83fdc0e505 to your computer and use it in GitHub Desktop.
AWS lambda function for automatic snapshots of EC2 instances
import json
import boto3
import json
import time
import datetime
ec2 = boto3.resource('ec2')
print('Loading function')
def lambda_handler(event, context):
for i in ec2.instances.all():
for tag in i.tags:
if tag['Key'] == 'Name':
instance_name = tag['Value']
print(instance_name)
vol_id = i.block_device_mappings[0]['Ebs']['VolumeId']
print(vol_id)
volume = ec2.Volume(vol_id)
print(volume.size)
snapshot = volume.create_snapshot()
tag = snapshot.create_tags(
Tags=[
{
'Key': 'Name',
'Value': instance_name
}
]
)
snps = ec2.snapshots.filter(
Filters=[
{
'Name': 'tag:Name',
'Values': [
instance_name,
]
}
]
)
for snp in snps:
if time.time() - int(time.mktime(snp.start_time.timetuple())) > 3600*24*7:
print("delete:", snp.snapshot_id)
snp.delete()
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment