Created
August 16, 2017 08:10
-
-
Save tsub/8fdd3d288ae79acd8c9692befc6d15ee to your computer and use it in GitHub Desktop.
Remove untagged images for ECR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
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
It works!