Clean Up GCP Cloud Run and Cloud Artifact

· ·

This site runs on GCP’s Cloud Run. When I want to add a post or make a change I use an automated script to build the new container and push it live. This leaves behind an old copy of the container—or revision in GCP’s parlance—which just sits there until you delete it. This script will delete all but the latest Cloud Run revision. Just a warning this will delete all inactive revisions in the current project.

# remove all but the latest cloud run revision
gcloud run revisions list --filter="status.conditions.type:Active AND status.conditions.status:'False'" --format='value(metadata.name)' | xargs -r -L1 gcloud run revisions delete --quiet

Once the above command completes, I run the another command to delete all but the latest Docker image in GCP’s Artifact Registry. It’s pretty hacky but it works. Hopefully Google will add an automated way to manage this in the future.

# remove all but the latest docker container in artifact registry
gcloud artifacts docker images list us-west1-docker.pkg.dev/development-258806/personal/personal-site --include-tags --filter="-tags:latest" | egrep '\b[A-Fa-f0-9]{64}\b' -o  | xargs -L 1 echo 'us-west1-docker.pkg.dev/development-258806/personal/personal-site@sha256:' | tr -d ' ' | xargs -L 1 gcloud artifacts docker images delete