3

GCP Container Registry is built on top of GCP Cloud Storage and one can set quite complex retention policies there.

However there's no such functionality in Container registry and as there's no disctinction between images in Storage (All the image file names are sha-hashes and are located in the same directory in the same bucket) one can't for example set a policy to retain only the last five versions of a single image.

Does anyone know if it's possible to set more complex retention policies to images in GCP and how one should do it?

Fleuri
  • 145
  • 12

1 Answers1

6

There seems to be currently no way to add retention policies to Container Registry. Deletion of extra images can however be automated by using gcloud. Here's a script I wrote that can be used as a cronjob: It iterates through the images and deletes all but five newest versions of an image.

#!/bin/bash

for image_name in $(gcloud container images list); do
    for digest in $(gcloud container images list-tags $image_name --format=json | awk '/digest/{ print $2 }' | sed -e 's/^"//' -e 's/.\{2\}$//' | tail -n +6); do 
            gcloud container images -q delete $image_name@$digest; 
    done;
done;

The number of preserved images can be changed by modifying tail's -n option, the value being +(N+1), N being the number of images one wants to preserve.

I'll provide a Kubernetes CronJob specification later.

EDIT: Here's the tool I made https://bitbucket.org/Fleuri/containerretention. Feel free to use!

Fleuri
  • 145
  • 12
  • 2
    I'll throw this into the mix as well, it's alpha but seems a bit more robust than a bash script. https://github.com/marekaf/gcr-lifecycle-policy – csgeek Mar 24 '21 at 20:40
  • Thanks for sharing! Looks very useful and it even accounts for Artifact Repository. – Fleuri Mar 26 '21 at 08:32