Use of $CI_COMMIT_REF_NAME in docker tag (suggested in documentation) is not always working
Summary
When using $CI_COMMIT_REF_NAME
in docker image tag naming in gitlab-ci.yml
, it will not work if the branch contains slashes.
Steps to reproduce
- Create a branch with slashes.
- In the branch, create a job that builds a docker image using the $CI_COMMIT_REF_NAME environment variable as the image tag, e.g.
CI_REGISTRY_IMAGE:
CI_COMMIT_REF_NAME and then push to GitLab. You will get a failure in the job.
What is the current bug behavior?
With a branch named feature/deploy_docker, this is the output from the CI job:
$ docker build --pull -t $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME .
invalid argument "registry.gitlab.com/userName/scrapy:feature/deploy_docker" for "-t, --tag" flag: invalid reference format
What is the expected correct behavior?
According to documentation, it recommends to use $CI_COMMIT_REF_NAME
variable to tag a docker image:
https://docs.gitlab.com/ce/ci/docker/using_docker_build.html#using-the-gitlab-container-registry
In this part of documentation, here is the statement:
Here, $CI_REGISTRY_IMAGE would be resolved to the address of the registry tied to this project, and $CI_COMMIT_REF_NAME would be resolved to the branch or tag name for this particular job. We also declare our own variable, $IMAGE_TAG, combining the two to save us some typing in the script section.
and the according gitlab-ci.yml
configuration shown as demonstration:
variables:
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME
before_script:
- docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
build:
stage: build
script:
- docker build -t $IMAGE_TAG .
- docker push $IMAGE_TAG
Other documentation is more thorough to mention that a branch can contain slashes, see for example here:
https://docs.gitlab.com/ee/ci/environments.html#dynamic-environments
So, the first part is review, followed by a / and then $CI_COMMIT_REF_NAME which takes the value of the branch name. Since $CI_COMMIT_REF_NAME itself may also contain /, or other characters that would be invalid in a domain name or URL, we use $CI_ENVIRONMENT_SLUG in the environment:url so that the environment can get a specific and distinct URL for each branch.
Also this documentation has a specific note about this:
https://docs.gitlab.com/ee/ci/yaml/#artifacts-name
Note: If your branch-name contains forward slashes (e.g. feature/my-feature) it is advised to use $CI_COMMIT_REF_SLUG instead of $CI_COMMIT_REF_NAME for proper naming of the artifact.
Maybe the documentation about using docker build should also rather use the $CI_ENVIRONMENT_SLUG than the $CI_COMMIT_REF_NAME?
Relevant logs and/or screenshots
See above.
Output of checks
This bug happens on GitLab.com
Results of GitLab environment info
n/a
Results of GitLab application Check
n/a
Possible fixes
Maybe the documentation about using docker build should also rather use the $CI_ENVIRONMENT_SLUG than the $CI_COMMIT_REF_NAME?