Skip to content

Instantly share code, notes, and snippets.

@Luzifer
Last active March 14, 2023 17:22
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/88b011fee7fff2f39f9d1684a46d7f9d to your computer and use it in GitHub Desktop.
Save Luzifer/88b011fee7fff2f39f9d1684a46d7f9d to your computer and use it in GitHub Desktop.
Remove old outdated repositories from DockerHub account
#!/usr/bin/env bash
set -euo pipefail
: ${USERNAME:=} # Username of the user to clean repos from
: ${TOKEN:=} # Token (or password) for the user to clean
: ${RETAIN_DAYS:=365} # How long to keep repos after last update
DEL_THRESH=$((RETAIN_DAYS * 24 * 3600))
[[ -n $USERNAME ]] || {
echo "Missing USERNAME" >&2
exit 1
}
[[ -n $TOKEN ]] || {
echo "Missing TOKEN" >&2
exit 1
}
token=$(
curl -sSfL -X POST \
-H 'Content-Type: application/json' \
--data-binary "{\"username\": \"${USERNAME}\", \"password\": \"${TOKEN}\"}" \
https://hub.docker.com/v2/users/login | jq -r '.token'
)
IFS=$'\n'
url="https://hub.docker.com/v2/repositories/${USERNAME}?page=1&page_size=25&ordering=last_updated"
while :; do
resp="$(curl -sSfL -X GET \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${token}" \
"${url}")"
for repo in $(echo "${resp}" | jq -c '.results[]'); do
name=$(echo "${repo}" | jq -r '.name')
echo -n "Found ${USERNAME}/${name}: " >&2
last_updated=$(date -d $(echo "${repo}" | jq -r '.last_updated') +%s)
[ $(($(date +%s) - last_updated)) -gt $DEL_THRESH ] || {
echo "Skipping (age)..." >&2
continue
}
status=$(echo "${repo}" | jq -r '.status')
[[ $status -ne 2 ]] || {
echo "Skipping (is deleting)..." >&2
continue
}
echo "Deleting..." >&2
curl -sSfL -X 'DELETE' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${token}" \
"https://hub.docker.com/v2/repositories/${USERNAME}/${name}/"
done
url="$(echo "${resp}" | jq -r '.next')"
[[ $url != null ]] || break
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment