Skip to content

Instantly share code, notes, and snippets.

@bmorrisondev
Created February 3, 2025 17:40
Show Gist options
  • Save bmorrisondev/7abacc5c7b6036d30aade29182f5ed11 to your computer and use it in GitHub Desktop.
Save bmorrisondev/7abacc5c7b6036d30aade29182f5ed11 to your computer and use it in GitHub Desktop.
A script to automatically remove unused images from a microk8s registry
#!/bin/bash
# Set variables
REGISTRY_URL="localhost:32000"
get_in_use_images() {
microk8s kubectl get pods --all-namespaces -o jsonpath='{.items[*].spec.containers[*].image}' | tr ' ' '\n' | sort | uniq
}
get_registry_images() {
curl -s "http://${REGISTRY_URL}/v2/_catalog" | jq -r '.repositories[]'
}
# Get the list of images in use by Kubernetes pods
in_use_images=$(get_in_use_images)
# Get the list of images in the registry
registry_images=$(get_registry_images)
# Find images in the registry that are not in use
unused_images=()
for image in $registry_images; do
image_used=false
for in_use_image in $in_use_images; do
if [[ "$in_use_image" == *"$image"* ]]; then
image_used=true
break
fi
done
if ! $image_used; then
unused_images+=("$image")
fi
done
get_tags() {
curl -s "http://${REGISTRY_URL}/v2/$1/tags/list" | jq -r '.tags[]'
}
get_digest() {
curl -sI -H "Accept: application/vnd.docker.distribution.manifest.v2+json" "http://${REGISTRY_URL}/v2/$1/manifests/$2" | grep Docker-Content-Digest | awk '{print $2}' | tr -d '\r'
}
delete_tagged_image() {
curl -sI -X DELETE "http://${REGISTRY_URL}/v2/$1/manifests/$2"
}
# Remove unused images from the registry
for unused_image in "${unused_images[@]}"; do
echo "Removing unused image: $unused_image"
# List all tags for the image
tags=$(get_tags $unused_image)
# Delete each tag of the image
for tag in $tags; do
digest=$(get_digest $unused_image $tag)
echo "Deleting $unused_image:$tag with digest $digest"
response=$(delete_tagged_image $unused_image $digest)
echo "Deleted $unused_image:$tag with response $response"
done
done
echo "Cleanup complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment