Skip to content

Instantly share code, notes, and snippets.

@hazcod
Last active May 13, 2020 11:27
Show Gist options
  • Save hazcod/232d4aa30d2778f0ab5cc0cd21a53281 to your computer and use it in GitHub Desktop.
Save hazcod/232d4aa30d2778f0ab5cc0cd21a53281 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