Alex Chesters


Cleaning Public ECR Repositories without Lifecycle Policies

Introduction

In late 2020 AWS announced ECR Public and the ECR Public Gallery . The experience as an engineer working with ECR Public Repositories is largely the same as using ECR Private Repositories, however there is one notable feature lacking - lifecycle policies.

Lifecycle Policies

ECR Lifecycle Policies are commonly used to prune unneeded images from an ECR repository (based on age of image or the amount of images stored in the repository). If you’ve used S3 Lifecycle , the concept is very similar.

A workaround

Whilst I recommend keeping an eye on the feature request for AWS to add Lifecycle Polices to ECR public, there is a workaround (for which you’ll need the AWS CLI v2 and jq ).

REPOSITORY_NAME=my-public-ecr-repository

IMAGES=$(aws ecr-public describe-images \
  --repository-name $REPOSITORY_NAME \
  --region us-east-1 | jq -r .imageDetails)

UNTAGGED_IMAGES=$(jq -r 'map(select(has("imageTags") | not))' <<< $IMAGES)

IMAGE_DIGESTS=$(jq -r '[.[] | "imageDigest=\(.imageDigest)"] | join(" ")' <<< $UNTAGGED_IMAGES)

aws ecr-public batch-delete-image \
  --repository-name $REPOSITORY_NAME \
  --image-ids $IMAGE_DIGESTS \
  --region us-east-1

This script works by fetching all images from a given ECR Public Repository, filtering out all the ones without tags (which usually indicates they’ve been superceded by a newer version) and deletes them.

I’ve started running this script in my CI pipelines after uploading to ECR Public to ensure that I don’t end up with lots of untagged images in my ECR Repositories costing me money unnecessarily.

Afterthoughts

Whilst this solution does work, I’m hoping that ECR Public soon adds support for Lifecycle Policies and I can pretend this script never happened. If you have a better idea in the meantime, you can always reach me via email (alex@cheste.rs ).