Check if image tag exists in Container Registry (GitHub)


Context

You are implementing an on-demand deployment of review environments (per-branch environments) to your infrastructure of choice using GitHub Actions. To save costs, and get faster feedback, you should consider verifying that the docker image tag is already available in the registry.

This brings the following benefits:

  • Faster feedback: The PR can be updated with a comment that no tag is found for the docker image
  • Cost: Avoids deploying an incomplete release to your system, since it will fail anyway due to the missing docker image tag.

Implementation

You have several alternatives to validate the existence of the tag in the registry:

  1. Pull the whole image with the tag by using docker pull <image>:<tag>
  2. Leverage the Container Registry API
  3. Use the GitHub Package REST API

In this Snippet, we are exploring Option #2, i.e obtaining the tag information via the Container Registry API

Option #1 is the easier option to implement. For larger images, it could take a significant amount of time (several minutes) to pull the image.

Option #3 implementation may have a similar level of complexity to the Option #2 discussed here

Using the Container Registry API

Using the GitHub Container Registry API implementation involves 2 main steps:

  1. Obtain a token to access the Container Registry with the correct scope by
TOKEN=$(curl -u <username>:<personal_access_token> https://ghcr.io/token\?scope\="repository:<repository/path>:pull" | jq -r .token)

The Personal Access Token used needs to have at leastread:packages permission to pull from the Container Registry

  1. Query the registry API about the existence of the tag

To query a particular tag, you can use the /v2/<repository/path/manifests endpoint as follows:

curl --head --fail -H "Authorization: Bearer $TOKEN" https://ghcr.io/v2/<repository/path>/manifests/<tag>

By using curl with --head request, it saves bandwidth and executes faster since it doesn’t need to receive the whole data available as part of this request.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.