How to extend an existing workflow in .gitlab-ci.yml

426 Views Asked by At

How can I extend an existing workflow by allowing one more rule? In my case the workflow checks if a variable is set to a value from a set of legal options. If that's not the case, no job should be allowed to run:

# base_workflow.yaml
workflow:
  rules: 
    - if: $JOB == "option1"
    - if: $JOB == "option2"
    - if: $JOB == "option3"

base_job:
  script:
    - # relies on legal value of $JOB
    - ...

I want to extend this workflow by allowing one more option:

# my_workflow.yaml

# .gitlab-ci.yml
include:
  - local: 'base_workflow.yaml'  # Include the external workflow file

my_job:
  script:
    - echo "This is my job"
  rules:
   - if: $JOB == "my_option"

This way the example does not work because the workflow doesn't allow a $JOB value of "my_option" and there is no way to extend the original workflow.

How can I achieve this without repeating the list from base_workflow.yaml (which may change) in my_workflow.yaml and without allowing the workflow to run if an illegal value for $JOB is used?

1

There are 1 best solutions below

0
On BEST ANSWER

You can try the !reference tags to achieve your goal.

In your base_workflow.yaml define your default rules:

# base_workflow.yaml
.default_rules:
  rules:
    - if: $JOB == "option1"
    - if: $JOB == "option2"
    - if: $JOB == "option3"

workflow:
  rules: 
    - !reference [.default_rules, rules]

base_job:
  script:
    - # relies on legal value of $JOB
    - ...

Your my_workflow.yaml file will be:

# my_workflow.yaml

# .gitlab-ci.yml
include:
  - local: 'base_workflow.yaml'  # Include the external workflow file

workflow:
  rules: 
    - if: $JOB == "my_option"
    - !reference [.default_rules, rules]

my_job:
  script:
    - echo "This is my job"

If the !reference tags don't work you will have to redefine your workflow in my_workflow.yaml with all the rules you need.

EDIT by OP: the !reference tag solution works! even though it gets expanded to:

workflow:
  rules:
  - if: $JOB == "my_option"
  - - if: $JOB == "option1"
    - if: $JOB == "option2"
    - if: $JOB == "option3"