Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I configure gitlab CI jobs to run on protected branches only?

Tags:

gitlab-ci

I am trying to configure a gitlab CI job to run only on the restricted branches, but I cannot find an only directive to do this.

like image 609
Louis Caron Avatar asked Feb 27 '19 08:02

Louis Caron


3 Answers

Using only:variables: combined with CI_COMMIT_REF_PROTECTED seems to be a good solution to your problem, but the details are difficult to determine without experimentation.

The documentation of the predefined variable CI_COMMIT_REF_PROTECTED is a bit unclear.

If the job is running on a protected branch

I expected CI_COMMIT_REF_PROTECTED to be set only if the branch is protected, but it appears that it is a boolean value instead. This means we should check for the string "true" rather than existence of the variable. See variables -> supported syntax, rule 1. Equality matching using a string.

Putting this together, I'd say a complete solution that clearly expresses your intentions would be:

only:
  refs:
    - branches
  variables:
    - $CI_COMMIT_REF_PROTECTED == "true"

The refs:branches is required if you don't want the job to run on protected tags.

like image 190
Fred Fettinger Avatar answered Nov 10 '22 18:11

Fred Fettinger


rules:if should be used.

rules:
  - if: '$CI_COMMIT_REF_PROTECTED == "true"'

only:variables: has been deprecated

like image 28
Jayd16 Avatar answered Nov 10 '22 18:11

Jayd16


In Gitlab 11.11 you can check this accessing the environment variable CI_COMMIT_REF_PROTECTED

only:
    variables:
        - $CI_COMMIT_REF_PROTECTED

Reference:

  • https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
  • https://docs.gitlab.com/ee/ci/yaml/#onlyexcept-advanced
like image 29
Erick Guillen Avatar answered Nov 10 '22 17:11

Erick Guillen