Day 19 – Cleanup unused AMI using Boto3
Welcome to Day 19 of 101 Days of DevOps. The topic for today is Cleanup unused AMI using Boto3.
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)
Please join me with my journey by following any of the below links
- Website: https://101daysofdevops.com/
- Twitter: @100daysofdevops OR @lakhera2015
- Facebook: https://www.facebook.com/groups/795382630808645/
- Medium: https://medium.com/@devopslearning
- GitHub: https://github.com/100daysofdevops/100daysofdevops
- YouTube Channel: https://www.youtube.com/user/laprashant/videos
- Slack: https://join.slack.com/t/100daysofdevops/shared_invite/zt-au03logz-YfDUp_FJF4rAUeDEbgWmsg
- Reddit: r/101DaysofDevops
- Meetup: https://www.meetup.com/100daysofdevops/