如果你push了一些commit到一个branch,但是这个branch是个merge reqeust的源分支,这时候就会触发两个pipeline,一个是因为push event,一个是因为merge request。通常情况下,我们希望只有一个,如何控制什么时候生成pipeline呢,这时候要用到一下配置方法:


使用workflow: 关键字, 决定是否生成一个pipeline


基本语法:


如果if后没有跟when,那么默认是alway,要执行。只要有一个条件是always,默认其他条件都被拒绝。所以这样设置其实是”放行“模式,也就是,没有设置的,统统不执行:


workflow:
  rules:
    - if: $CI_COMMIT_MESSAGE =~ /-draft$/
      when: never
    - if: '$CI_PIPELINE_SOURCE == "push"'
CODE


上面的这个workflow只有push代码的时候,commit信息没有 ”-draft" 字样,就会触发pipeline,其他类型的pipeline,merge request, 手动启动,api启动, 定时启动统统不行。



如果最后条件没有if,之后when,always,就是封堵模式,也就是说,除了上面列出的不行外,其他的都行:


workflow:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "schedule"'
      when: never
    - if: '$CI_PIPELINE_SOURCE == "push"'
      when: never
    - when: always
CODE

以上就是所有的定时pipeline都不执行, 所有的push都不执行,其他的如merge request, 手动, api都可以。


分支pipeline模板:(不触发merge request pipeline)

https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Workflows/Branch-Pipelines.gitlab-ci.yml

# To contribute improvements to CI/CD templates, please follow the Development guide at:
# https://docs.gitlab.com/ee/development/cicd/templates.html
# This specific template is located at:
# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Workflows/Branch-Pipelines.gitlab-ci.yml

# Read more on when to use this template at
# https://docs.gitlab.com/ee/ci/yaml/#workflowrules

workflow:
  rules:
    - if: $CI_COMMIT_TAG
    - if: $CI_COMMIT_BRANCH

CODE



也可以用 include

include:
  - template: 'Workflows/Branch-Pipelines.gitlab-ci.yml'
CODE


merge request pipeline(不再生成branch pipeline)

https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Workflows/MergeRequest-Pipelines.gitlab-ci.yml

# To contribute improvements to CI/CD templates, please follow the Development guide at:
# https://docs.gitlab.com/ee/development/cicd/templates.html
# This specific template is located at:
# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Workflows/MergeRequest-Pipelines.gitlab-ci.yml

# Read more on when to use this template at
# https://docs.gitlab.com/ee/ci/yaml/#workflowrules

workflow:
  rules:
    - if: $CI_MERGE_REQUEST_IID
    - if: $CI_COMMIT_TAG
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

CODE


也可以用 include

include:
  - template: 'Workflows/MergeRequest-Pipelines.gitlab-ci.yml'
CODE


有merge request的情况下,触发merge request pipeline, 没有的时候触发branch pipeline


workflow:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
    - if: '$CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS'
      when: never
    - if: '$CI_COMMIT_BRANCH'
CODE