Python Script to Clean up Old Images From AWS ECR using Boto3
For one of my projects, I automated building and pushing AWS ECR images using Github Actions, but soon realized that my AWS ECR repo had a pile-up of unused images. In my workflows, I use the most recently image and other images in the repository present a minor opportunity for optimization. Since, AWS ECR charges you based on the storage size, cleaning up old images will save me a few bucks.
In this short post, I will share a Python script that is quite handy for cleaning up old/unused images from AWS ECR.
Python Boto3 Script
First create a ecr-cleanup directory to hold the requirements.txt and main.py files. We will use
boto3 library for fetching image details in a repo and deleting them. So first create a requirements.txt file with the following contents:
| |
You can install the dependency using the following command:
| |
Next, create a main.py file and add the following code snippet to it:
| |
The script performs the following operations:
- It reads the
REPO_NAMEenvironment variable which corresponds to the AWS ECR repo name. - Next, it fetches all images from the repo using the
fetch_all_images. - The
sort_images_by_push_datereturns a sorted list of images based on their push date. - Finally,
delete_imagesis invoked to delete all images except the last one.
You can run the script using the following command:
| |
Note: The script assumes that you have configured AWS credentials on your shell before executing it.
That’s it for this post. I hope you find this post useful!