Skip to content

Instantly share code, notes, and snippets.

@smnbbrv
Last active April 17, 2023 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 smnbbrv/55cc0b2a0a30f56f7744fe75fbf9676c to your computer and use it in GitHub Desktop.
Save smnbbrv/55cc0b2a0a30f56f7744fe75fbf9676c to your computer and use it in GitHub Desktop.
Cleanup semver docker images in nexus repository
#!/bin/bash
# credits to https://gist.github.com/sfwn/7453e78be0374b3d53f1e44f5bb8beef
# TODO replace ghead with head for non-macos
# TODO provide DOCKER_LOGIN and DOCKER_PASSWORD as arguments
DOCKER_REGISTRY="https://docker.example.com/v2"
DOCKER_LOGIN="xxx"
DOCKER_PASSWORD="yyy"
LAST_TAGS_TO_KEEP=10
DRY_RUN=true
ACCEPT_HEADER="Accept: application/vnd.docker.distribution.manifest.v2+json"
BASIC_AUTH="$DOCKER_LOGIN:$DOCKER_PASSWORD"
function get_repositories {
curl -u $BASIC_AUTH -Ls "$DOCKER_REGISTRY/_catalog?n=10000" | jq -r '."repositories"[]'
}
function get_repository_tags {
REPOSITORY="$1"
curl -u $BASIC_AUTH -Ls "$DOCKER_REGISTRY/$REPOSITORY/tags/list?n=10000" | jq -r '."tags"[]' | grep -E '^\d+(\.\d+)?(\.\d+)?$' | sort -t "." -k1,1n -k2,2n -k3,3n | ghead -n -$LAST_TAGS_TO_KEEP
}
function get_tag_digest {
REPOSITORY="$1"
TAG="$2"
curl -u $BASIC_AUTH -ILs --header "${ACCEPT_HEADER}" "${DOCKER_REGISTRY}"/"${REPOSITORY}"/manifests/"${TAG}" | grep -i Docker-Content-Digest | awk '{print $2}' | tr -d '\r'
}
function separator {
echo -------------------------------------------------------------------------------------
}
REPORITORIES=$(get_repositories)
echo ALL REPOS: ${REPORITORIES}
for REPOSITORY in ${REPORITORIES[@]}
do
separator
TAGS=$(get_repository_tags "$REPOSITORY")
echo "Repository $REPOSITORY: found following tags for removal:"
echo "$TAGS"
for TAG in ${TAGS[@]}
do
separator
echo "Processing $REPOSITORY:$TAG"
if [[ $TAG == latest ]]; then
echo "Skipping tag"
else
DIGEST=$(get_tag_digest "${REPOSITORY}" "${TAG}")
URL="${DOCKER_REGISTRY}"/"${REPOSITORY}"/manifests/"${DIGEST}"
if [[ $DRY_RUN == true ]]; then
echo "DRY RUN: Deleting tag, manifest url: $URL"
else
echo "Deleting tag, manifest url: $URL"
curl -u $BASIC_AUTH -s -X DELETE -i $URL
fi
fi
done
done
@smnbbrv
Copy link
Author

smnbbrv commented Apr 17, 2023

Removes all but LAST_TAGS_TO_KEEP of only semantic-versioned docker images from the Nexus repository (latest and any non-semver tag is preserved).

Requires jq, curl and GNU-head (macos only)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment