When you are building custom AMI’s in AWS account you will need to manage them by deleting the old AMI’s and keep only few latest images. For this you can use the below python code in Lambda function. I took the below code as reference from here and modified it to delete the AMI’s by filtering the images which has only specified tags.
Filtering the images with tags is important as different teams/projects will be having their images and it avoids accidental deletion of the wrong images.
Note: Before executing this code make sure your AMI’s are tagged.
* First import libraries datetime, boto3 and time.
* Next get the ec2 connection session using boto3.
* Assign a variable older_days and pass the value as days (all images which are older than specified days from the present date will be filtered)
* Invoke the main function lambda_handler and then
* Invoke the function get_ami_list by passing older_days as a parameter
* Function get_ami_list uses ec2 descirbe_images to get all the images details which has specified ownerid as the owner
* Next it will invoke the function get_delete_date, calculates and finds out the date which is 5 days past from the present date
* Next the images will be filtered according to the specified tag value and if the image is older then 5 days.
* Then images are further filtered if older than 5 days and deregistered by invoking function delete_ami
from datetime import datetime, timedelta, timezone import boto3 import time client.ec2 = boto3.client('ec2', region_name='us-east-1') #Here all images which are older than 5 days from the present date will be filtered older_days = 5 def lambda_handler(event, context): get_ami_list(older_days) def get_ami_list(older_days): amiNames = client.ec2.describe_images(Owners=['123456789123']) print(amiNames) today_date = datetime.now().strftime('%d-%m-%Y') print("Today's date is " + today_date) deldate1 = get_delete_date(older_days) print("AMI images which are older than " + str(deldate1) + " will be deregistered") for image in amiNames['Images']: taginfo = image['Tags'] for tagName in taginfo: #Filter only the images having tag value as Proj1AMI if (tagName['Value'] == 'Proj1AMI'): ami_creation = image['CreationDate'] imageID = image['ImageId'] print("=================================================") print("Image id is " + imageID) print("Creation date for above image is " + ami_creation) if (str(ami_creation) < str(get_delete_date(older_days))): print("This AMI is older than " + str(older_days) + " days") delete_ami(imageID) def get_delete_date(older_days): delete_time = datetime.now(tz=timezone.utc) - timedelta(days=older_days) return delete_time; def delete_ami(imageID): print("Deregistering Image ID: " + imageID) client.ec2.deregister_image(ImageId=imageID)