Skip to content

Instantly share code, notes, and snippets.

@dabio
Last active January 8, 2018 19:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dabio/961cb755c9556537dec70ab9a79fbeb6 to your computer and use it in GitHub Desktop.
Save dabio/961cb755c9556537dec70ab9a79fbeb6 to your computer and use it in GitHub Desktop.
Cleanup outdated ECR images
#!/bin/bash
set -o pipefail # the exit status of the last failed command gets returned
set -o nounset # exit when using undeclared variables
# Defaults
REPO=""
VERBOSE=0
PROFILE="default"
KEEP_IMAGES=3
function show_help() {
cat > /dev/stdout << END
${0} -r <repo> [-n <number of images>] [-p <profile>] [-v] [-h]
REQUIRED ARGS:
-r - ecr repository name, eg vaola/fog (required)
OPTIONAL ARGS:
-n - number of images to keep (default=${KEEP_IMAGES})
-p - aws profile (default=${PROFILE})
-v - verbose logging (default off)
-h - show help
END
}
while getopts "h?v:n:p:r:" opt
do
case "${opt}" in
h|\?)
show_help
exit 0
;;
v) VERBOSE=1 ;;
n) KEEP_IMAGES=${OPTARG} ;;
p) PROFILE=${OPTARG} ;;
r) REPO=${OPTARG} ;;
esac
done
shift "$((OPTIND-1))"
if [[ ${REPO} = "" ]]
then
show_help
exit 1
fi
if [[ ${VERBOSE} -gt 0 ]]
then
set -x
fi
BUILD_DIR_BASE=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
mkdir -p "${BUILD_DIR_BASE}"
RAW_FILE="${BUILD_DIR_BASE}/raw"
IMAGES_FILE="${BUILD_DIR_BASE}/images"
IMAGES_SORTED_FILE="${BUILD_DIR_BASE}/images_sorted"
function cleanup() {
rm -fr "${BUILD_DIR_BASE}"
}
trap cleanup TERM INT QUIT
aws ecr describe-images --repository-name ${REPO} --profile ${PROFILE} --output text > $RAW_FILE
while read line; do
rows=($line)
if [[ "${rows[0]}" != "IMAGEDETAILS" ]]; then
continue
fi
echo "${rows[2]} ${rows[5]} ${rows[1]}" >> ${IMAGES_FILE}
done < ${RAW_FILE}
sort -ro ${IMAGES_SORTED_FILE} ${IMAGES_FILE}
COUNT=0
while read line; do
rows=($line)
if [ "$COUNT" -ge "${KEEP_IMAGES}" ]; then
aws ecr batch-delete-image --repository-name ${rows[1]} --profile ${PROFILE} --image-ids imageDigest=${rows[2]}
fi
(( COUNT++ ))
done < ${IMAGES_SORTED_FILE}
cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment