How do I test if a specific tag of a docker image already exists in gcr.io?

3/25/2019

I've noticed with gcr.io that when I push a docker image with a specific tag:

gcr.io/myproject/myimage:mytag

If that image/tag combo already exists, it seems to untag the original image, upload the new one, and apply the tag to the new one.

This is leading to my repo becoming bloating with lots of untagged versions of the same image.

How do I test if the image/tag combo already exist in gcr.io, so that I only push when it's required?

-- Andy
docker
gcloud
google-container-registry
google-kubernetes-engine

3 Answers

5/18/2019

Here's how I solved this in a shell script

existing_tags=$(gcloud container images list-tags --filter="tags:mytag" --format=json gcr.io/myproject/myimage)

if [[ "$existing_tags" == "[]" ]]; then
  printf "tag does not exist"
else
  printf "tag exists"
fi

Explanation

I'm using gcloud container images list-tags (documentation here)

  • And filtering for tags matching mytag using the --filter flag

  • And formatting as JSON using --format=json

So essentially, if the tag mytag doesn't exist, the output of this will be an empty array [], otherwise, it does exist. You can test this really simply just by string comparison in your script, and then proceed accordingly.

-- davnicwil
Source: StackOverflow

6/27/2019

There are a few good answers above. But I just wanna give 1 more option that I'm using.

#!/bin/bash

REPO_URL=gcr.io/myproject/myimage
TAG=mytag

TAG_EXISTING="$(gcloud container images list-tags --format='get(tags)' $REPO_URL | grep $TAG)"
if [ -z $TAG_EXISTING ]
then
    docker push $REPO_URL:$TAG
fi
-- Viet Tran
Source: StackOverflow

3/25/2019

Method 1: Assuming your docker command has the gcr credentials, you can try to pull the image like docker pull gcr.io/foo/image:tag. This would be slow, but it's a guaranteed way.

Method 2: Assuming gcloud is present in your environment, you could run gcloud container images list-tags [- -format=json] gcr.io/foo/image and see if the output has the tag you want.

Method 3: If these two solutions aren't good enough for you, you can learn how to use your Google Cloud Service Account as a docker username/password here, and then use the Docker Registry v2 API to List Image Tags or just directly Query the image manifest for pulling the image with the tag.

For example, if you had an gcr.io/foo/alpine:v1 image, to test this using cURL and a temporary access_token (obtained via gcloud), you could run:

TOKEN="$(gcloud config config-helper --format 'value(credential.access_token)')"

curl -H "Authorization: Bearer $TOKEN" \
    https://gcr.io/v2/foo/alpine/manifests/v1

and if you get an 200 OK response, it means that tag exists.

-- AhmetB - Google
Source: StackOverflow