Day 19 –101 Days of DevOps — Cleanup unused AMI using Boto3

Prashant Lakhera
2 min readJul 19, 2021

Welcome to Day 19 of 101 Days of DevOps. The topic for today is Cleanup unused AMI using Boto3.

To view the complete course, please check the below url.

For more info, register via the below link

YouTube Channel link

This is another common use case we use to encounter daily DevOps jobs where we need to clean up unused AMI per company policy(e.g., every 30 or 60 days). One of the primary reasons to do that is to save costs.

To write this code, we need to follow the series of steps

Step1: Importing the standard library boto3, dateutil.parser, and datetime module.

import boto3
from datetime import datetime
from dateutil.parser import parse

Step2: Create the IAM client

client = boto3.client("iam")

The code to cleanup AMI follows the same logic as we followed on Day 18 to rotate IAM keys https://www.101daysofdevops.com/courses/101-days-of-devops/lessons/day-18/. The only difference is the method we are going to use to do that.

Step3: In the next step, we are going to use describe_images to get the image attribute. Make sure set Owners=’self’ else; it will return the publicly available image too.

my_ami = client.describe_images(Owners=['self'])['Images']

Step4: Then, we will iterate over it and get important attributes like ami creation date and ami id.

for ami in my_ami:
creation_date=ami['CreationDate']
creation_date_parse=parse(creation_date).replace(tzinfo=None)
ami_id = ami['ImageId']

Step5: Then, we will calculate the current date and the difference between the current date and ami creation date

current_date=datetime.now()
diff_in_days = (current_date - creation_date_parse).days

Step6: If this diff is greater than the company defined policy(in this case, I am using 2 but completely dependent on your company policy), then deregister the image using deregister_image() method.

if diff_in_days > 2:
client.deregister_image(ImageId=ami_id)

GitHub link:

https://github.com/100daysofdevops/100daysofdevops/blob/master/boto3/cleanup_old_ami/cleanup_old_ami.py

Please join me with my journey by following any of the below links

--

--

Prashant Lakhera

AWS Community Builder, Ex-Redhat, Author, Blogger, YouTuber, RHCA, RHCDS, RHCE, Docker Certified,4XAWS, CCNA, MCP, Certified Jenkins, Terraform Certified, 1XGCP