Skip to content

Instantly share code, notes, and snippets.

@ShakataGaNai
Created December 19, 2017 18:19
Show Gist options
  • Save ShakataGaNai/8ce4f520f8dfacb2f971eeea1e9cebb4 to your computer and use it in GitHub Desktop.
Save ShakataGaNai/8ce4f520f8dfacb2f971eeea1e9cebb4 to your computer and use it in GitHub Desktop.
import boto3
import re
import datetime
import time
ec = boto3.client('ec2')
iam = boto3.client('iam')
def backupVols(e):
print("Looking for volumes to backup")
todate = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H%M%SZ")
vols = e.volumes.all()
for vol in vols:
backup = 0
for tags in vol.tags:
if(tags["Key"].strip().lower() == "backup"):
backup = int(tags["Value"])
if backup > 0:
backupName = "autosnap_{}_{}".format(todate,vol.id)
exp = time.time()+(int(backup) * 86400)
setTags = {"originalVol":vol.id,"utcnow":time.time(),"expiresOn":exp}
takesnap(e, vol.id, backupName, setTags)
def takesnap(e, vol, name, tags):
fullTags = [{'Key': 'Name', 'Value': name},{'Key': 'ebs-autosnap', 'Value': 'true'}]
for k,v in tags.items():
fullTags.append({"Key":k, "Value":str(v)})
snap = e.create_snapshot(VolumeId=vol, Description="EBS Autosnap")
snap.create_tags(Resources=[snap.id], Tags=fullTags)
print("Vol: {} -- Snap Id: {}".format(vol,snap.id))
def expireSnaps(e):
print("Looking for expired snapshots")
snaps = e.snapshots.filter(Filters=[{'Name': 'tag:ebs-autosnap', 'Values': ['true'] }] )
now = time.time()
for snap in snaps:
for tag in snap.tags:
if(tag["Key"] == "expiresOn"):
exp = float(tag["Value"])
if exp < now:
print("Snapshot {} expired".format(snap.id))
snap.delete()
def lambda_handler(event, context):
regions = [region['RegionName'] for region in ec.describe_regions()['Regions']]
#regions = ['us-east-1']
for region in regions:
print("Running Region {}".format(region))
e = boto3.resource('ec2', region_name=region)
backupVols(e)
expireSnaps(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment