'Assigning predefined variable to global variable

I have following pipeline that is a template for others, that is why I want to assign CI_DEFAULT_BRANCH as default value to TARGET_BRANCH that can be then overriden by other branch name (develop, release etc.) if needed.

Preconditions:

Project default branch is master

Pipeline runs on master branch

variables:
  TARGET_BRANCH: $CI_DEFAULT_BRANCH # The name of the project’s default branch. = master

stages:
  - build

build:
  stage: build
  rules:
    - if: '$CI_COMMIT_BRANCH == $TARGET_BRANCH' # CI_COMMIT_BRANCH is master
  script:
    - echo hello
    - 'dir env:'

Using this approach the job is not included in the pipeline, but changing the variable like this:

  TARGET_BRANCH: "master"

adds the job to the pipeline.

The script section has the command to list all variables and their values in powershell. Both CI_COMMIT_BRANCH and TARGET_BRANCH have value master in both cases, but still on the first scenario rules:if does not seem to be true. Can someone explain why?



Solution 1:[1]

Assigning predefined variable to global variable

Yes you can. As you saw in the script clause of a job your TARGET_BRANCH variable had successfully taken the value of CI_DEFAULT_BRANCH. By assigning it in the variables section

BUT

The issue is where this is available.

variables:
  TARGET_BRANCH: $CI_DEFAULT_BRANCH

The TARGET_BRANCH will have the value of CI_DEFAULT_BRANCH only in the scope of a Gitlab job. And the rules are not in this scope.

AND

This does not happen only to predefined variables. Try this

TARGET_BRANCH: "master"
MY_VAR: $TARGET_BRANCH

Even though TARGET_BRANCH is populated, MY_VAR will show the exact same behavior, meaning it wont be available in rules section.

Basically, in the variables section when you assign to a varialbe another variable. The proper expansion will happen only to the scope of a job. ie script section

In the variables section if you want it to work as you intend, you need to pass literal strings not variables

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tolis Gerodimos