Skip to content
pbb.io/blog

TIL how to use a variable as the default for another variable in GitLab CI

November 4, 2024
1 min read
GitLab CI

In GitLab CI, the variables block does not expand other variables at definition time. So this does not work as expected:

variables:
DEPLOY_USER: "${DEPLOY_USER:-$CI_REGISTRY_USER}"
DEPLOY_TOKEN: "${DEPLOY_TOKEN:-$CI_JOB_TOKEN}"

The $CI_REGISTRY_USER and $CI_JOB_TOKEN references won’t be resolved in the variables block because GitLab CI doesn’t support nested variable expansion there.

The fix is to move the fallback logic into before_script, where normal shell expansion applies:

before_script:
- export DEPLOY_USER="${DEPLOY_USER:-$CI_REGISTRY_USER}"
- export DEPLOY_TOKEN="${DEPLOY_TOKEN:-$CI_JOB_TOKEN}"

This is especially relevant when writing reusable CI templates where you want to allow overriding a variable but fall back to a CI-provided default.

Back to posts

GitLab CI
Phil-Bastian Berndt

Phil-Bastian Berndt
Tech Lead at Naymspace