Skip to content

Instantly share code, notes, and snippets.

@samehmohamed88
Created January 17, 2018 18:12
Show Gist options
  • Save samehmohamed88/b7d24fc782c74a59791d4ce15f2b2a11 to your computer and use it in GitHub Desktop.
Save samehmohamed88/b7d24fc782c74a59791d4ce15f2b2a11 to your computer and use it in GitHub Desktop.
import boto3
import collections
import time
import sys
from datetime import datetime, timedelta
myAccount = boto3.client('sts').get_caller_identity()['Account']
def lambda_handler(event, context):
retention_period = 14
date = datetime.now()
retention_date = datetime.today() - timedelta(days=retention_period)
images = ec2.describe_images(
Filters=
[{
'Name': 'tag-key', 'Values': ['DeleteOn']
}]).get('Images')
if images:
print "Found %d instances that need evaluated" % len(images)
for image in images:
try:
string_date = [
t.get('Value') for t in image['Tags']
if t['Key'] == 'DeleteOn'][0]
delete_date = time.strptime(string_date, "%m-%d-%Y")
except IndexError:
delete_date = None
if delete_date and retention_date > delete_date:
snapshots = ec2.describe_snapshots(
OwnerIds=[myAccount],
Filters=
[{
"Name" : "Description", 'Values' : ['*{}*'.format(image['ImageId'])]
}]).get('Snapshots')
amiResponse = ec2.deregister_image(
DryRun=False,
ImageId=image['ImageId'],
)
for snapshot in snapshots:
snap = ec2.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
else:
print "No current backup found. Termination suspended."
# uncomment to test locally; we don't need contenxt here
# lambda_handler(False, False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment