Skip to content

Instantly share code, notes, and snippets.

@tsub
Created August 16, 2017 08:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tsub/8fdd3d288ae79acd8c9692befc6d15ee to your computer and use it in GitHub Desktop.
Save tsub/8fdd3d288ae79acd8c9692befc6d15ee to your computer and use it in GitHub Desktop.
Remove untagged images for ECR
#!/bin/sh
set -eu
type aws > /dev/null 2>&1 && type jq > /dev/null 2>&1 || {
echo 'Required aws-cli and jq'
exit 1
}
repositories=$(aws ecr describe-repositories --query 'repositories[*].repositoryName' | tr -d "[\",\t\n\r\"]")
for repository in $repositories; do
echo "$repository: Deleting untagged images"
nextToken="initialized"
while [ "$nextToken" != "null" ]; do
if [ "$nextToken" == "initialized" ]; then
response=$(aws ecr list-images --repository-name $repository --filter tagStatus=UNTAGGED --max-items 100)
else
response=$(aws ecr list-images --repository-name $repository --filter tagStatus=UNTAGGED --max-items 100 --starting-token $nextToken)
fi
nextToken=$(echo $response | jq -r '.NextToken')
untaggedImages=$(echo $response | jq -c '.imageIds')
if [ "$untaggedImages" == "[]" ]; then
echo "$repository: Untagged image not found"
break
fi
aws ecr batch-delete-image --repository-name $repository --image-ids $untaggedImages
done
echo "$repository: Deleted untagged images"
done
@baragona
Copy link

It works!

@cablespaghetti
Copy link

Didn't work for me initially because my default output format for the AWS CLI is configured as text. Adding this line to the top of the script fixed it for me: export AWS_DEFAULT_OUTPUT=json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment