Skip to content

Instantly share code, notes, and snippets.

@rbramwell
Forked from hazcod/cloudbuild.yaml
Last active January 23, 2020 14:18
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 rbramwell/043ce0699feb3910b571062c71ffdd11 to your computer and use it in GitHub Desktop.
Save rbramwell/043ce0699feb3910b571062c71ffdd11 to your computer and use it in GitHub Desktop.
Clean container registry images in Google Cloud Build step.
substitutions:
_IMG_KEEP: "3"
steps:
- name: 'gcr.io/cloud-builders/gcloud-slim'
entrypoint: 'bash'
args:
- '-c'
- |
set -e
apt update && apt install -y jq
images="myimage"
for image in ${images[@]}; do
echo "Cleaning image ${image}"
c=0
image="gcr.io/$PROJECT_ID/${image}"
number_keep_images=${_IMG_KEEP}
date=$(gcloud container images list-tags $image --limit=unlimited \
--sort-by=~TIMESTAMP --format=json | TZ=/usr/share/zoneinfo/UTC jq -r '.['$number_keep_images'].timestamp.datetime | sub("(?<before>.*):"; .before ) | strptime("%Y-%m-%d %H:%M:%S%z") | mktime | strftime("%Y-%m-%d")')
for digest in $(gcloud container images list-tags $image --limit=unlimited --sort-by=~TIMESTAMP \
--filter="timestamp.datetime < '${date}'" --format='get(digest)'); do
(
set -x
gcloud container images delete -q --force-delete-tags "${image}@${digest}"
)
c=c+1
done
echo "Deleted ${c} images for ${image}." >&2
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment