GitLab CI/CD run step only if on correct branch AND it has changes

Viewed 3259

I want a step in the build process only to run on the master branch, if there where changes to the src folder.

My .gitlab-ci.yml file thus contains:

build:php:
    stage: build
    image: alpine
    interruptible: true
    needs: [ "test:php" ]
    script:
        - do stuff // abreviated for simplicity
    rules:
        -   if: $LANGUAGE_RELEASE
            when: never
        -   if: '$CI_COMMIT_REF_SLUG == "master"' # run for production test branch
        -   changes:
                - src/*

However, the issue here is, that it also runs on the dev branch, when I change anything.

Question: Is the a way to have this step only run, both conditions (the branch and the changes) are met?

2 Answers

When using the rules keyword, the rules:if clause may be used, with the variable $CI_COMMIT_BRANCH.

Thus, something like below to specify master as the only branch to run the job:

build:php:
    stage: build
    # ...
    rules:
       - if: '$CI_COMMIT_BRANCH == "master"'
    # ...

(Rules are applied in order)

The documentation reference for common if clauses available is here.


Now to combine an if and changes rule, you'll need to use

build:php:
    stage: build
    # ...
    rules:
       - if: '$CI_COMMIT_BRANCH == "master"'
         changes:
           - file1 # single file
           - folder/**/* # folder including all files and subfolders
    # ...

You can read more about changes used in rules here and read the full changes specification here.

With the initial setup there where two issues:

  1. the changes where seen as a new rule (since they had a - in front)
  2. src/* only takes the src folder in consideration, not sub folders, for that you'll need src/**/*

It is also possible to use the only keyword to specify master as the only branch to run the job. Despite being simple, this is no longer encouraged and it cannot be used together with rules (only/except reference).

Example:

build:php:
    stage: build
    # ...
    only:
       - master
    # ...

There is no way to run rules:changes on the master branch.

Gitlab docs says:

You should use rules: changes only with branch pipelines or merge request pipelines. You can use rules: changes with other pipeline types, but rules: changes always evaluates to true when there is no Git push event. Tag pipelines, scheduled pipelines, manual pipelines, and so on do not have a Git push event associated with them.

It means changes gives always true if there is different type than branches or merge_requests

Related