How to delete untagged images in ECR

3.3k Views Asked by At

After pushing docker image(with test tag) to ECR, more than one time, older docker images goes untagged in ECR

What is the AWS CLI command to delete untagged image in ECR?

3

There are 3 best solutions below

4
Arun Kamalanathan On

What happens is when you publish an image:tag the tag will be removed from the previous image.

You can run a CLI command to identify the images that are untagged and pipe the output to the command to delete those.

You can also use lifecycle policies.

Refer the link below. I haven't tested this myself.

reference: How to delete untagged images from AWS ECR Container Registry

https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html

1
GOPESH CHAUDHARY On

You can try using aws cli - set the correct AWS REGION where your ecr repositories exists.

AWSREGION=us-west-2 && ecr describe-repositories --region=$AWSREGION --output text | awk '$5{print $5}' | sed -n  's/.*repository\/\(.*\)/\1/p' | while read line; do aws ecr list-images --region=$AWSREGION --repository-name "$line" --filter tagStatus=UNTAGGED --query 'imageIds[*]' --output text | while read imageId; do aws ecr batch-delete-image  --region=$AWSREGION --repository-name "$line" --image-ids imageDigest=$imageId; done; done

This command will delete all the untagged images recursively. Hope this solves your problem.

0
Sahar On

You can use ECR lifecycle policy, which has been recently added by AWS https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html

Here's an example of a policy to only keep one untagged image and expire all others ECR policy rule