Skip to content

Instantly share code, notes, and snippets.

@OksanaH
Created Jan 29, 2022
Embed
What would you like to do?
Lambda handler
def lambda_handler(event, context):
amis_in_use = []
total_amis_deleted = 0
total_snapshots_deleted = 0
try:
regions = event['regions']
max_ami_age_to_prevent_deletion = event['max_ami_age_to_prevent_deletion']
filters = makeAmiFilters(event['ami_tags'])
for region in regions:
amis_in_use = list(set(imagesInASGs(region) + imagesUsedInEC2s(region)))
ec2 = boto3.client('ec2', region_name = region)
amis = ec2.describe_images(
Owners = ['self'],
Filters = filters
).get('Images')
for ami in amis:
now = datetime.now()
ami_id = ami['ImageId']
img_creation_datetime = datetime.strptime(ami['CreationDate'], '%Y-%m-%dT%H:%M:%S.%fZ')
days_since_creation = (now - img_creation_datetime).days
if ami_id not in amis_in_use and days_since_creation > max_ami_age_to_prevent_deletion:
ec2.deregister_image(ImageId = ami_id)
total_amis_deleted += 1
for ebs in ami['BlockDeviceMappings']:
if 'Ebs' in ebs:
snapshot_id = ebs['Ebs']['SnapshotId']
ec2.delete_snapshot(SnapshotId=snapshot_id)
total_snapshots_deleted += 1
print(f"Deleted {total_amis_deleted} AMIs and {total_snapshots_deleted} EBS snapshots")
except Exception as e:
send_alert(f"AMI cleaner failure", e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment