How to check if a container image exists on GHCR?

I’m using GHCR as my container registry. The GitOps automation we use breaks if an engineer specifies an image that doesn’t exist. For example, if the last built image is ghcr.io/my-company/my-image:1.0 but the engineer specifies ghcr.io/my-company/my-image:1.1 the automation breaks.

Is there a way use the GHCR v2 http API or the GitHub API to check if a specific image/tag combination exists? And what PAT scopes are needed for the check (if it is available)?

GHCR supports the Docker Registry API. You could either try to download the specific tag and see if you get a valid manifest, or retrieve the list of tags and check if the tag shows up. You’ll need to use a token with read:packages scope for the requests.

That said, maybe it’s better to catch and handle the error that currently occurs instead of adding a separate check? After all, the error occurring already tells you that the tag doesn’t exist. :wink:

I’m asking specifically because other topics reference portions of the Docker Registry API that haven’t been implemented yet (e.g. /v2/_catalog - Ghcr.io docker HTTP API). When I attempt to use the /v2/<name>/tags/list API endpoint, I get {"errors":[{"code":"UNAUTHORIZED","message":"authentication token not provided"}]}. But using the same username and PAT I’m able to successfully access the /v2/ API endpoint. I double-checked that the user has Read access to the GHCR package that I’m trying to access.

Additionally, we are using a third-party GitOps package which breaks when it tries to install an image that doesn’t exist. So we’re opting to check the GitOps definition during the lint/test phrase before even executing the GitOps process.

You can use the tags/list endpoint to grab all available tags.

You’ll need a token for this like a PAT. (soon this will work with the GITHUB_TOKEN)

Here’s an example:

# for a public image you can get a fake NOOP token to use
curl https://ghcr.io/token\?scope\="repository:USER/IMAGE:pull"
{"token":"{TOKEN}"}
curl -H "Authorization: Bearer {TOKEN}" https://ghcr.io/v2/USER/IMAGE/tags/list
{"name":"USER/IMAGE","tags":["2.7.5-arm64","2.7.5-armhf","2.7.5-amd64"]}
3 Likes