Skip to content

Instantly share code, notes, and snippets.

@Luzifer
Last active February 24, 2023 19:48
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 Luzifer/d16b8d40468cdc4b9100d85114352ccb to your computer and use it in GitHub Desktop.
Save Luzifer/d16b8d40468cdc4b9100d85114352ccb to your computer and use it in GitHub Desktop.
Cleanup script for untagged revisions in GCR repos
#!/bin/bash
set -euo pipefail
: ${DELETE_OLDER_THAN:=0} # When to delete tags by time (days)
: ${PROJECT:=${1:-}} # Which project to clean
COLOR_RED="\033[0;31m"
COLOR_GREEN="\033[0;32m"
COLOR_CYAN="\033[0;36m"
COLOR_YELLOW="\033[0;33m"
COLOR_PLAIN="\033[0m"
function error() {
echo -e "${COLOR_RED}$@${COLOR_PLAIN}" >&2
}
function fail() {
error "$@"
exit 1
}
function fetch_gcr_auth() {
jq -r '.auths."gcr.io".auth' ~/.docker/config.json | base64 -d
}
function info() {
echo -e "${COLOR_CYAN}$@${COLOR_PLAIN}" >&2
}
function request() {
curl -su "$(fetch_gcr_auth)" "$@"
}
function step() {
info "[$(date +%H:%M:%S)] $(printf "%${script_level:-0}s" '' | tr ' ' '+')$@"
}
function success() {
echo -e "${COLOR_GREEN}$@${COLOR_PLAIN}" >&2
}
[ -n "${PROJECT}" ] || fail "Please specify the project name as parameter 1 or PROJECT env-var"
DEL_TS=0
[ $DELETE_OLDER_THAN -eq 0 ] || DEL_TS=$((($(date +%s) - DELETE_OLDER_THAN * 86400) * 1000))
step "Retrieving repos..."
for repo in $(request "https://gcr.io/v2/_catalog" | jq -r ".repositories | .[] | select(. | contains(\"${PROJECT}\"))"); do
step "Listing manifests in repo '${repo}'..."
manifests=$(request "https://gcr.io/v2/${repo}/tags/list")
step "Searching for untagged manifests..."
for digest in $(echo "${manifests}" | jq --arg ts ${DEL_TS} -r '.manifest | to_entries | .[] | select(.value.tag == [] or .value.timeUploadedMs < $ts) | .key'); do
for tag in $(echo "${manifests}" | jq --arg digest ${digest} -r '.manifest[$digest].tag[]'); do
step "Deleting tag '${tag}' from '${digest}' in '${repo}'..."
request -X DELETE "https://gcr.io/v2/${repo}/manifests/${tag}" >/dev/null && success "Deleted" || error "Deletion failed"
done
step "Deleting manifest '${digest}' from repo '${repo}'..."
request -X DELETE "https://gcr.io/v2/${repo}/manifests/${digest}" >/dev/null && success "Deleted" || error "Deletion failed"
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment