Search code examples
gitlabgitlab-cipipeline

And operator for GitLab `only` pipeline directive


I am aware of the fact that one can run a GitLab pipeline only when a certain condition is satisfied, eg. only when the branch is master or only when a Git Tag is created.

For example:

stages:
  - greet

greet_job:
  stage: greet
  only:
    - master
  script:
    - echo "Hello!"

This runs the greet_job job only when the branch is called master.

I would like to combine two conditions with a logical and, ie. I would like to run a pipeline, say, only when the branch is called master and a new Git Tag has been created. Is that possible?

ADDED

Here I found a possible solution:

  - greet

greet_job:
  stage: greet
  only:
    refs:
      - master
      - tags
    variables:
      - $CI_COMMIT_BRANCH == "master"
  script:
    - echo "Hello!"

Solution

  • You can build fairly complex conditions with rules, which you use should anyway as work on only/except is discontinued.

    You can combine two conditions in rules with the && operator, so e.g. run the job only on merge-requests and if $CUSTOM_VARIABLE is true.

     rules:
        - if: '$CUSTOM_VARIABLE == "true" && $CI_PIPELINE_SOURCE == "merge_request_event"'
    

    But checking if the branch is master and a tag was created is not trivial, as there are no predefined varariables for the branch from which a tag was created.

    So if you only create tags from master, checking if the pipeline is a tag pipeline wpuld be sufficient.

    stages:
      - greet
    
    greet_job:
      stage: greet
      script:
        - echo "Hello!"
      rules:
        - if: '$CI_COMMIT_TAG'