Gitlab CI 根据 MR 中更改的文件有条件地覆盖模板变量

Gitlab CI conditionally override a template variable based on which files were changes in a MR

我有这样的模板:

/templates/.copy-echo.yml:

workflow:
  rules:
    - if: '$CI_COMMIT_REF_NAME == "master"'

variables:
  FILE_PATH: /test_conf_1.txt
  DESTINATION_HOST: somehost

stages:
  - copy
  - echo

copy step 1/2:
  rules:
    - changes:
        - ${FILE_PATH}
  stage: copy
  script: |
    echo "Add copy here!"

copy step 2/2:
  rules:
    - changes:
        - ${FILE_PATH}
  stage: echo
  script: |
    printenv
    echo ${DESTINATION_HOST}

现在在我的 .gitlab-ci.yml:

include: '/templates/copy-echo.yml'

variables:
  FILE_PATH: /test_conf_1.txt
  DESTINATION_HOST: somehost2

现在我想要的是根据合并请求中更改的文件有条件地为 DESTINATION_HOST 变量赋值。

例如如果合并请求对文件 test_conf_2.txt 进行了更新,则 DESTINATION_HOST 的值应为 somehost2,如果合并请求对文件 test_conf_3.txt 进行了更新,则 [=15] 的值应为 somehost2 =] 应该是 somehost3.

是否有可能实现这一目标,如果可以,如何实现? TIA!

您可以使用rules:variableshttps://docs.gitlab.com/ee/ci/yaml/#rulesvariables
示例:

my job:
  script: printenv
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        - test_conf_2.txt
      variables:
        DESTINATION_HOST: "somehost2"
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        - test_conf_3.txt
      variables:
        DESTINATION_HOST: "somehost3"

但如果您手动启动管道,它就不起作用:

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. A rules: changes job is always added to those pipelines if there is no if that limits the job to branch or merge request pipelines.