How to delete untagged images from AWS ECR Container Registry

Andrea Baccega picture Andrea Baccega · Dec 3, 2016 · Viewed 13k times · Source

When pushing images to Amazon ECR, if the tag already exists within the repo the old image remains within the registry but goes in an untagged state.

So if i docker push image/haha:1.0.0 the second time i do this (provided that something changes) the first image gets untagged from AWS ECR.

Is there a way to safely clean up all the registries from untagged images?

Answer

nfvs picture nfvs · Feb 6, 2017

You can delete all images in a single request, without loops:

IMAGES_TO_DELETE=$( aws ecr list-images --region $ECR_REGION --repository-name $ECR_REPO --filter "tagStatus=UNTAGGED" --query 'imageIds[*]' --output json )

aws ecr batch-delete-image --region $ECR_REGION --repository-name $ECR_REPO --image-ids "$IMAGES_TO_DELETE" || true

First it gets a list of images that are untagged, in json format:

[ {"imageDigest": "sha256:..."}, {"imageDigest": "sha256:..."}, ... ]

Then it sends that list to batch-image-delete.

The last || true is required to avoid an error code when there are no untagged images.