Created
November 18, 2019 15:43
-
-
Save lmayorga1980/2fc905010e6e419a4b8dfb7d12d028c1 to your computer and use it in GitHub Desktop.
Cleanup Old AMIS
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
from __future__ import print_function | |
import json | |
import boto3 | |
import logging | |
from datetime import datetime, timedelta | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
def get_outdated_images(): | |
outdated_images = set() | |
ec2 = boto3.resource('ec2') | |
#filter images only from the local account | |
images = ec2.images.filter(Owners=['self']) | |
for image in images: | |
#convert timestamp into specific format | |
created_at = datetime.strptime( | |
image.creation_date, | |
"%Y-%m-%dT%H:%M:%S.000Z", | |
) | |
#if older than 30 days, add to the outdated_images | |
if created_at < datetime.now() - timedelta(30): | |
outdated_images.add(image.id) | |
return outdated_images | |
def set_decommission_tag(list_images): | |
for image_id in list_images: | |
ec2 = boto3.resource('ec2') | |
image = ec2.Image(image_id) | |
print("Ready to tag image:" + image.image_id) | |
#NOTE: ReadyToDecomission Tag is overwritten if manually changed | |
image.create_tags(DryRun=False,Tags=[ | |
{ | |
'Key': 'ReadyToDecomission', | |
'Value': 'True' | |
}, | |
{ 'Key': 'Certified', | |
'Value', 'False' | |
}]) | |
#This can return the amis that are referenced by running ec2 instances | |
def set_images_with_referenced_ec2_instances(list_images): | |
ec2 = boto3.resource('ec2') | |
instances = ec2.instances.all() | |
for instance in instances: | |
if instance.image_id in list_images: #search if any instance is using it as a reference | |
image = ec2.Image(instance.image_id) | |
image.create_tags(DryRun=False,Tags=[ | |
{ | |
'Key': 'ReadyToDecomission', | |
'Value': 'False' | |
}]) | |
else: | |
logger.error("INFO: InstanceId: " + instance.instance_id + " with SourceAmiId: " + instance.image_id + " not in the list of Owned AMIs or AMI it not old enough" ) | |
def execute_image_cleanup(): | |
#get the list of images that are outdated | |
list_image_ids = get_outdated_images() | |
#set the tag for decommission | |
set_decommission_tag(list_image_ids) | |
#skip images that are currently used | |
set_images_with_referenced_ec2_instances(list_image_ids) | |
ec2 = boto3.resource('ec2') | |
images = ec2.images.filter(Owners=['self'], Tag =['ReadyToDecomission=True','ReferencedByEc2=False']) | |
for image in images: | |
logger.info("INFO:" + "Removing AMI with ID:" + image.image_id) | |
image.deregister() | |
#NOTE: Call SNS Topic to notify that an AMI has been deregistered | |
def lambda_handler(event, context): | |
execute_image_cleanup() | |
return { | |
'statusCode': 200, | |
'body': json.dumps('AMI Cleanup Process is complete') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment