Skip to content

Instantly share code, notes, and snippets.

@riccardomc
Created November 29, 2018 10:11
Show Gist options
  • Save riccardomc/aab7be753a7ce72ecd010def228b04b4 to your computer and use it in GitHub Desktop.
Save riccardomc/aab7be753a7ce72ecd010def228b04b4 to your computer and use it in GitHub Desktop.
Delete older images in AWS ECR
#!/bin/bash
#
# Go through every repository and delete N older images where N > $LIMIT
#
# i.e. LIMIT=700 ./checkecr2.sh
#
set -e
# Limit
LIMIT=${LIMIT:-500}
DRY_RUN=${DRY_RUN:-}
# Colors
GREEN='\033[0;32m'
NC='\033[0m' # No Color
RED='\033[0;31m'
YELLOW='\033[2;33m'
WORKDIR=$(mktemp -d)
trap "rm -rf $WORKDIR" EXIT ERR INT TERM
repositories=$(aws ecr describe-repositories --query 'sort_by(repositories, &repositoryName)[*].repositoryName' | jq -r '.[]')
for repository in $repositories
do
echo -en "${YELLOW}Processing \"${repository}\""
images_count=$(aws ecr describe-images --repository-name $repository --query 'sort_by(imageDetails, &imagePushedAt)[*].imageDigest' | jq -r '.[]' | tee $WORKDIR/images | wc -l)
if [ $images_count -gt $LIMIT ]
then
digests_to_delete_count=$(( images_count - LIMIT ))
echo -e "${YELLOW} Purging ${digests_to_delete_count} digest(s) from ${repository}${NC}"
chunks=$(( $digests_to_delete_count / 100 + 1 ))
chunk_size=$(( $digests_to_delete_count / $chunks ))
head -n $digests_to_delete_count $WORKDIR/images | split -l $chunk_size - $WORKDIR/digests
for d in $(ls -1 $WORKDIR/digests*) ; do
digests=$(sed 's/^\(.*\)$/imageDigest=\1/' $d | tr '\n' ' ' )
if [ ! -z "${DRY_RUN}" ] ; then
echo aws ecr batch-delete-image --repository-name $repository --image-ids $digests
else
aws ecr batch-delete-image --repository-name $repository --image-ids $digests > /dev/null
fi
done
rm -rf $WORKDIR/digests*
else
echo -e " ${GREEN}Ok${NC}"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment