Skip to content

Instantly share code, notes, and snippets.

@pandorasNox
Last active July 4, 2023 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pandorasNox/183b1c62036d323edba5b1ae4de20816 to your computer and use it in GitHub Desktop.
Save pandorasNox/183b1c62036d323edba5b1ae4de20816 to your computer and use it in GitHub Desktop.
gitlab rules examples

gitlab rules examples

# .gitlab-ci.yml

image: alpine:latest

only on branches:
  rules:
    - if: '$CI_COMMIT_TAG == null'
  script:
    - echo only on branches
    - env

only on tags:
  rules:
    - if: '$CI_COMMIT_TAG != null'
  script:
    - echo only on tags
    - env
job:
  script: echo "Hello, Rules!"
  rules:
    - if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/ && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME != $CI_DEFAULT_BRANCH
      when: never
    - if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/
      when: manual
      allow_failure: true
    - if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME
docker build:
  script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        - Dockerfile
      when: manual
      allow_failure: true

notes on if in rules

  • if any found rule is evaluated to be true ever rule after it is not evaluated anymore
  • e.g. first rule adds pipeline job then job/pipeline is definitly added, even if there is a later rule excluding it
  • e.g. first rule found to be evaluated to true is a rule containing when: never means nothing is added and also all rules after are not considered anymore bec this rules was evaluated true
  • that implies: order of rules matter

workflow rules

# https://docs.gitlab.com/ee/ci/yaml/workflow.html#switch-between-branch-pipelines-and-merge-request-pipelines
# Tell GitLab to only run one pipeline at a time for a commit:
# - a branch pipeline when a merge request is not open for the branch
# - a merge request pipeline when a merge request is open for the branch
workflow:
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
      when: never
    - if: $CI_COMMIT_BRANCH

other rules examples

# rules: # examples
- if: $CI_COMMIT_BRANCH == "my-branch-name-xyz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment