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.
You have several alternatives to validate the existence of the tag in the registry:
- Pull the whole image with the tag by using
docker pull <image>:<tag>
- Leverage the Container Registry API
- 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:
- 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 least
read:packages permission to pull from the Container Registry
- 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>
--head request, it saves bandwidth and executes faster since it doesn’t need to receive the whole data available as part of this request.
- GitHub Community – How to check if a container image exist
- [Authentication example against the Container Registry API]https://github.com/goharbor/harbor/issues/13653#issuecomment-736650920)
- Container Registry API Spec
- Container Registry API -Manifest Endpoint
- GitHub – Create a Personal Access Token