Why would a variable in a template NOT work when building on a branch?

I’m facing a weird issue and have no clue what I might have done incorrectly. I’ve set up a templated .gitlab-ci.yml file that is used by multiple projects (seen below). It works perfectly if it runs against the “main” branch in several repos. However, if someone creates a development branch, it fails 100% of the time from any branch other than main. I’m sure I simply have something configured incorrectly, but I can’t seem to find anything when doing searches either here or via Google; so please don’t flame me if this has been asked a million times.

Here is the task definition in the templated .gitlab-ci.yml file:

build_image:
  image: ${CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX}/docker:cli
  stage: release
  tags:
    - docker
  services:
    - name: ${CI_DEPENDENCY_PROXY_DIRECT_GROUP_IMAGE_PREFIX}/docker:dind
      alias: docker
  variables:
    DOCKER_HOST: tcp://docker:2375/
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: ""
    ARTIFACT_FQN: $CI_REGISTRY/$CI_REGISTRY_IMAGE
  before_script:
    - export DOCKER_HOST=tcp://docker:2375 docker info
    - echo $ARTIFACT_FQN
    - echo "$CI_REGISTRY"
    - echo "$CI_REGISTRY_IMAGE"
    - echo "${CI_REGISTRY_TOKEN:?}" | docker login -u "${CI_REGISTRY_USER:?}" --password-stdin -- "${CI_REGISTRY:?}"
  script:
    - |
      if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
        tag=""
        echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = ':latest'"
      else
        tag=":$CI_COMMIT_REF_SLUG"
        echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag"
      fi
    - docker build --pull -t "$ARTIFACT_FQN${tag}" .
    - docker push "$ARTIFACT_FQN${tag}"
  rules:
    - if: $CI_COMMIT_BRANCH
      exists:
        - Dockerfile

It fails 100% of the time on the before_script docker login line. With the debugging info added (as shown here), I get an error from a running pipeline that says the CI_REGISTRY_TOKEN variable isn’t set; i.e.:

$ echo "${CI_REGISTRY_TOKEN:?}" | docker login -u "${CI_REGISTRY_USER:?}" --password-stdin -- "${CI_REGISTRY:?}"

[34](https://gitlab.myserver.com/myproject/services/user-service/-/jobs/1166#L34)/bin/sh: eval: line 160: CI_REGISTRY_TOKEN: parameter not set or null

[35](https://gitlab.myserver.com/myproject/services/user-service/-/jobs/1166#L35)Error: Cannot perform an interactive login from a non TTY device

BUT, it ONLY fails this way when building from a BRANCH… main is always successful.

Any suggestions on what I need to look at?

Thanks in advance!!!

Check to see if the CI_REGISTRY_TOKEN variable is configured to be protected. If it is, then it won’t be available to unprotected branches. See GitLab CI/CD variables - Protect a CI/CD variable | GitLab for detail on protected variables.

That was it! I guess I interpreted “protected” to mean it isn’t printed in pipeline output, similar to a password. Obviously, I was wrong! Thank you, thank you!