Skip to content

Instantly share code, notes, and snippets.

@guessi
Created May 15, 2017 02:11
Show Gist options
  • Save guessi/f80680cec9724c6482b4873399bcc746 to your computer and use it in GitHub Desktop.
Save guessi/f80680cec9724c6482b4873399bcc746 to your computer and use it in GitHub Desktop.
AWS ECR - Cleanup Untaaged Image
#!/bin/bash
CLEANUP=${1:-false}
echo
echo "CLEANUP: ${CLEANUP}"
echo
aws configure list --profile ecr >/dev/null 2>&1
if [ $? -ne 0 ]; then
echo "Abort: aws profile [ecr] not found"
exit 1
fi
if [ "${CLEANUP}" = "true" ]; then
echo " Warning: it is to scan and remove all Untagged images on ECR"
echo " please hit [any key] to continue, or [CTRL-C] twice to abort"
read
fi
# sleep few seconds for having chance to cancel [^C][^C]
sleep 3
echo "scanning for images without tag..."
echo
echo "+--------------------------------------------------------------------------+-------------------+"
echo "| repository name | image with no-tag |"
echo "+--------------------------------------------------------------------------+-------------------+"
repos=$(aws --profile ecr ecr describe-repositories \
--query 'repositories[*].repositoryName' \
--output json | jq -r '. | sort | .[]')
for repo in ${repos}; do
count=$(aws --profile ecr ecr list-images \
--repository-name "${repo}" \
--filter tagStatus=UNTAGGED \
--query 'imageIds[*]' \
--output text | wc -l)
printf "| %-72s | %-17s |\n" "${repo}" "${count}"
if [ "${CLEANUP}" = "true" ]; then
for image in $(aws --profile ecr ecr list-images \
--repository-name ${repo} \
--filter tagStatus=UNTAGGED \
--query 'imageIds[*]' \
--output text )
do
aws --profile ecr ecr batch-delete-image \
--repository-name ${repo} \
--image-ids imageDigest=${image}
done
fi
done
echo "+--------------------------------------------------------------------------+-------------------+"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment