Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/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
Add Comment
Please, Sign In to add comment