ph1psG
ph1psG

Reputation: 738

Gitlab CI/CD workflow rule variables only allow one if condition

I am currently trying to structure my .gitlab-ci.yml file like following:

In order to avoid putting these rules in the jobs directly (in reality there are about 30 jobs) I want to reuse those rules globally. I could not find a better way other than using workflow:rules.

workflow:
  rules:
    - if $CI_COMMIT_BRANCH == "develop"
      variables:
        RUN_A: "true"
    - if $CI_COMMIT_BRANCH == "develop" && $CI_PIPELINE_SOURCE == "web"
      variables:
        RUN_B: "true"

job-a:
  rules:
    - if: $RUN_A == "true"
  script:
    - exit 0

job-b:
  rules:
    - if: $RUN_B == "true"
  script:
    - exit 0

The problem is, that if there is a web trigger on develop, it will not set "RUN_B" to true. It will just have "RUN_A" with true. I added another job to print out the variables just to make sure:

test:
  image: alpine
  script:
    - echo $RUN_A
    - echo $RUN_B

This will only print true for RUN_A but nothing for RUN_B. I could not find anything in Gitlabs documentation that states it will only use the first matching rule. Anyhow, is there a better way to handle this? What am I missing?

Upvotes: 2

Views: 4759

Answers (1)

Mouson Chen
Mouson Chen

Reputation: 1224

Because GitLab ci Rules evaluated in order until the first match.

in your first rule if $CI_COMMIT_BRANCH == "develop" is match, the pipeline is create, in this times variable RUN_A: "true" is set, but variable RUN_B is undefined.

In your case, you can modify your .gitlab-ci.yml. variable setting and rules order.

workflow:
  rules:
    - if: $CI_COMMIT_BRANCH == "develop" && $CI_PIPELINE_SOURCE == "web"
      variables:
        RUN_B: "true"
        RUN_A: "true"
    - if: $CI_COMMIT_BRANCH == "develop"
      variables:
        RUN_A: "true"

default:
  image: alpine

job-a:
  rules:
    - if: $RUN_A == "true"
  script:
    - exit 0

job-b:
  rules:
    - if: $RUN_B == "true"
  script:
    - exit 0

test:
  script:
    - echo $RUN_A
    - echo $RUN_B

Upvotes: 5

Related Questions