Using Google Cloud Container Registry is pretty easy.
See my previous post: Cloud Migration: Move Your Application to Google Kubernetes Engine.
But as time go by, you get more and more images accumulating in the container registry.
To delete the images, you can manually delete each image, which is OK for a single image removal, but frustrating if you want to remove multiple images.
I have created a short script to remove images recursively from a specific container registry folder.
#!/usr/bin/env bash
set -e
REPO=gcr.io/MY_PROJECT/MY_GCR_FOLDER
deleteTag() {
NAME=$1
HASH=$2
echo "delete hash ${NAME} ${HASH}"
gcloud container images delete -q --force-delete-tags ${NAME}@${HASH}
}
deleteTags() {
NAME=$1
echo "scan tags for ${NAME}"
gcloud container images list-tags ${NAME} --format='get(digest)' | while read line; do deleteTag $NAME $line; done
}
deleteImages() {
NAME=$1
echo "scan images for ${NAME}"
gcloud container images list --repository=${NAME} | grep -v ^NAME | while read line; do deleteImages $line; done
deleteTags ${NAME}
}
deleteImages ${REPO}
To run the script, supply the following as an argument: gcr.io/MY_PROJECT/MY_GCR_FOLDER.
The script will recursively delete the folder and files under this folder.
Update: keep the latest version
To keep the latest version for each image, change the following functions:
deleteTag() {
LATEST=$1
NAME=$2
HASH=$3
TAG=$4
if [[ "${LATEST}" == "${TAG}" || "latest" == "${TAG}" ]]; then
echo "skip delete of ${NAME} ${TAG}"
return 0
fi
echo "delete hash ${NAME} ${TAG} ${HASH}"
gcloud container images delete -q --force-delete-tags ${NAME}@${HASH}
}
deleteTags() {
NAME=$1
echo "scan tags for ${NAME}"
LATEST=$(gcloud container images list-tags ${NAME} --format='get(tags)' | sort -n | tail -1)
echo "keeping latest: ${LATEST}"
gcloud container images list-tags ${NAME} --format='get(digest,tags)' | while read line; do deleteTag $LATEST $NAME $line; done
}
No comments:
Post a Comment