-
-
Save OksanaH/e8a9ff885132e54f5233e6b0c817bf0f to your computer and use it in GitHub Desktop.
Lambda handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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