Skip to content

Instantly share code, notes, and snippets.

@triangletodd
Last active May 24, 2019 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save triangletodd/887cbd3ab231b02852bc5465b7f06c5d to your computer and use it in GitHub Desktop.
Save triangletodd/887cbd3ab231b02852bc5465b7f06c5d to your computer and use it in GitHub Desktop.
GCR Image Cleanup - list or delete all but the 5 newest tags for all images in a GCR repository
#!/usr/bin/env bash
# Exit if no arguments are passed
if [ $# -lt 1 ]; then
cat << HELP
gcr_cleanup -- list or delete all but the 5 newest tags for all images
EXAMPLE:
- list all but the 5 newest tags for all images
gcr_cleanup gcr.io/project-name
- delete all but the 5 newest tags for all images
FINAL_ANSWER=doittoit gcr_cleanup gcr.io/project-name
HELP
exit 0
fi
# List all images in the repo
images() {
gcloud container images list --repository "$1" --format='value(name)'
}
# List all tags for an image, excluding the 5 newest
# If an image has 5 or less tags, this will return nothing
image_tags() {
gcloud container images list-tags "$1" --format='value(tags)' --sort-by='~timestamp' | tail -n +6
}
# Prints the tags that need to be cleaned up
# Will delete them for you if you set the FINAL_ANSWER environment variable to "doittoit"
main() {
for image in $(images "$1"); do
for tag in $(image_tags "$image"); do
IFS=','
for innertag in $tag; do
if [[ $FINAL_ANSWER == 'doittoit' ]]; then
gcloud container images untag "$image:$innertag"
else
echo "$image:$innertag"
fi
done
unset IFS
done
done
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment