Search code examples
gitlabgitlab-cigitlab-ci-runnergitlab-ce

Why is Gitlab CICD workflow:rules:if:variables failing to set variables?


stages:
  - test

# Default vars
variables:
  DEPLOY_VARIABLE: "dev-deploy"

workflow:
  rules:
    - if: '$CI_COMMIT_REF_NAME == "master"'
      variables:
        DEPLOY_VARIABLE: "master-deploy"  # Override globally-defined DEPLOY_VARIABLE

my_project_test:
  stage: test
  script:
    - env | grep CI
    - echo $DEPLOY_VARIABLE // this always outputs dev-deploy.

Running with gitlab-runner 14.10.1.

No matter if i try that locally or on Gitlab that var is never set.

On local I run it with gitlab-runner exec shell my_project_test.

env | grep CI is:

CI_SERVER_VERSION=
CI_RUNNER_EXECUTABLE_ARCH=darwin/amd64
CI_COMMIT_REF_NAME=master
CI_JOB_TOKEN=
CI_PROJECT_ID=0
CI_RUNNER_REVISION=f761588f
... etc

As per their documentation: If a rule matches, when: always is the default, and when: never is the default if nothing matches.

I even tried if: '1 == 1' and so on.


Solution

  • gitlab-runner exec has several limitations and does not implement/consider many features of YAML definitions, including workflow:rules:[]variables in this case.

    However, when run through gitlab.com or a self-hosted instance of GitLab, workflow:rules: will evaluate properly.

    Keep in mind, there are a few cases where variables set elsewhere will take precedence over variables defined in the YAML, such as when variables are set in project, group, or instance settings.