#Automated Image Cleanup for Amazon ECR The Python script and Lambda function described here help clean up images in Amazon ECR. The script looks for images that are not used in running Amazon ECS tasks that can be deleted. You can configure the script to print the image list first to confirm deletions, specify a region, or specify a number of images to keep for potential rollbacks.
Configuring the AWS Command Line Interface.
To prevent any problems with your system Python version conflicting with the application, we recommend using virtualenv.
Install Python:
pip install python 3
Install virtualenv:
$ pip install virtualenv
$ virtualenv -p PATH_TO_YOUR_PYTHON_3 cloudformtion
$ virtualenv ~/.virtualenvs/cloudformtion
$ source ~/.virtualenvs/cloudformtion/bin/activate
- CD to the folder that contains main.py.
- Run the following command:
pip install -r requirements.txt -t {THE_FOLDER_PATH}
- Compress the contents of folder (not the folder).
- Run the following command:
aws lambda create-function --function-name {NAME_OF_FUNCTION} --runtime python2.7 --role {ARN_NUMBER} --handler main.handler --timeout 15 --zip-file fileb://{ZIP_FILE_PATH}
-
Run the following command:
aws lambda update-function-code --function-name {NAME_OF_FUNCTION} --zip-file fileb://{ZIP_FILE_PATH}
Prints the images that are not used by running tasks and which are older than the last 100 versions, in all regions:
python main.py
Deletes the images that are not used by running tasks and which are older than the last 100 versions, in all regions:
python main.py –dryrun False
Deletes the images that are not used by running tasks and which are older than the last 20 versions (in each repository), in all regions:
python main.py –dryrun False –imagestokeep 20
Deletes the images that are not used by running tasks and which are older than the last 20 versions (in each repository), in Oregon only:
python main.py –dryrun False –imagestokeep 20 –region us-west-2