Search code examples
yamlgitlab-ci

How to merge rules on a GitLab CI Job


Let's suppose I have this hidden "base" job.

.base_job:
  rules:
    - if: "$CI_COMMIT_TAG"
      when: never
    - if: '$CI_PIPELINE_SOURCE == "web"'

I'd like to add these rules to a new job and be able to extend them too, e.g.:

job_1:
  rules:
    - <add .base_job here>
    - if: "$CI_MERGE_REQUEST_IID"


job_2:
  rules:
    - <add .base_job here>
    - if: "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH"

Note that job_1 and job_2 have different rules, including the ones from .base_job.

If I were to use extends, the jobs would have only the custom rule because according to the docs:
You can use extends to merge hashes but not arrays.

My solution so far is to copy-paste the rules for both jobs but I'd like to keep it more DRY.

Any tips on how to do it?


Solution

  • As pointed out in the question, the GitLab CI extends construct does not allow one to merge inner arrays (and more generally the expected underlying feature in YAML is not(yet) available), so basically:

    .base_job:
      rules:
        - if: "$CI_COMMIT_TAG"
          when: never
        - if: '$CI_PIPELINE_SOURCE == "web"'
    
    job_1:
      extends: .base_job
      rules:
        - if: "$CI_MERGE_REQUEST_IID"
    

    would lead to:

    job_1:
      rules:
        - if: "$CI_MERGE_REQUEST_IID"
      # → overwritten
    

    Alternative solution

    However, if you find that the first answer posted is too hacky and too verbose, it appears you could just use the native YAML anchors construct to do the same.

    Namely, you might write a GitLab CI conf-file like this:

    .base_job:
      rules:
        - &rule_a
          if: "$CI_COMMIT_TAG"
          when: never
        - &rule_b
          if: '$CI_PIPELINE_SOURCE == "web"'
    job_a:
      rules:
        - *rule_a
        - if: "$CI_MERGE_REQUEST_IID"
    job_b:
      rules:
        - *rule_b
        - if: "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH"