Skip to content

Instantly share code, notes, and snippets.

@henriquecarv
Last active July 24, 2020 13:13
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 henriquecarv/3290ba971cee05938c4cf97a84c4e752 to your computer and use it in GitHub Desktop.
Save henriquecarv/3290ba971cee05938c4cf97a84c4e752 to your computer and use it in GitHub Desktop.
Remove multiple GCP Docker registry images
#!/bin/bash
GOOGLE_PROJECT_ID="example-id"
GCLOUD_SERVICE_KEY="serviceAccount.json content"
# eu.grc.io, etc...
ZONE="gcr.io"
SERVICE_ACCOUNT_FILE_NAME="google_service_account.json"
function gcp_auth {
echo "${GCLOUD_SERVICE_KEY}" | base64 -d > $SERVICE_ACCOUNT_FILE_NAME
gcloud auth activate-service-account --key-file=$SERVICE_ACCOUNT_FILE_NAME
gcloud config set project $GOOGLE_PROJECT_ID
}
function delete_images {
# example-folder-name
local REPOSITORY_FOLDER="${1}"
local REPOSITORY="${ZONE}/${GOOGLE_PROJECT_ID}/${REPOSITORY_FOLDER}"
local IMAGES=$(gcloud container images list --repository=$REPOSITORY --format='get(name)')
# 10 = KEEPS LAST 10 IMAGES
local NUMBER_OF_IMAGES_TO_KEEP="${2}"
for image in $IMAGES
do
echo "current image: ${image}"
DIGEST_TO_REMOVE=$(gcloud container images list-tags ${image} --sort-by=~TIMESTAMP --format='get(digest)'|tail + $NUMBER_OF_IMAGES_TO_KEEP)
for digest in $DIGEST_TO_REMOVE
do
gcloud container images delete -q --force-delete-tags "${image}@${digest}"
done
done
}
function clear_auth_file {
rm $SERVICE_ACCOUNT_FILE_NAME
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment