【问题标题】:Is there a way to use OR condition with needs in GitLab CI job有没有办法在 GitLab CI 工作中根据需要使用 OR 条件
【发布时间】:2022-10-07 06:11:12
【问题描述】:

我正在尝试使用 \".gitlab.ci.yml\" 文件中的 \"needs\" 为先前阶段的作业创建具有 \"OR\" 条件的作业依赖项,但无法找到解决方案。

.gitlab-ci.yml 文件->

stages:
  - build
  - test
  - deploy


Build_job:      
  stage: build
  script:
    - echo \"hello from build job\"

Test_job1:
  stage: test
  script:
    - echo \"Start test 1\"
  when: manual

Test_job2:
  stage: test
  script:
    - echo \"Start test 2\"
  when: manual

Deploy_job:
  stage: deploy
  script:
    - echo \"Start deploying the job\"
  when: manual
    needs:
      - job: Test_job1
        optional: true
      - job: Test_job2
        optional: true

我的目标是 Test_job1Test_job2 通过 Deploy_job 应该启用。 但是使用上面的代码,我无法这样做,因为只有当前两个测试作业都通过时,Deploy_job 才会启用。

有没有办法可以使用像needs: [Test_job1 or Test_job2] 这样的东西?

  • 我认为这应该通过在您的Test_job 定义中添加:allow_failure: true 来解决。但是,如果您计划以包含使用 rules 关键字的方式扩展配置,则需要小心,因为这可能会干扰 when 的作业级定义

标签: gitlab gitlab-ci


【解决方案1】:

needs:optional: 关键字名称容易混淆。用于在工作时设置needs: 要求可能不存在由于其他管道/作业逻辑(作业可以可选存在)。 但是,任何可选的 needs:job: 名称存在于管道中的都是必需的。

我看到了一些选择到您想要的管道:

自动化路径

您可以在 Test_job 作业中使用 rules: 关键字有条件地将它们添加到管道中。

决定运行哪个 Test_job 的人(基于您使用when: manual 的事实的假设)可能遵循某种决策逻辑 - 或者团队可以决定预设的决策逻辑。然后,您将该逻辑构建到您的 needs:if: 条件中,以确定您的 Test_job# 工作是否存在在管道中——那么Deploy_job: 将只需要添加到管道中的 Test_jobs。

例如,如果一个测试应该在您的默认分支上运行而另一个在功能分支上运行,您可以使用以下命令自动运行相关的 Test_job 并让 Deploy_job 依赖它:

Test_job1:
  stage: test
  script:
    - echo "Start test 1"
  # this job is only added for pipelines on the default branch
  rules:
    - if $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
      when: on_success
    - when: never

Test_job2:
  stage: test
  script:
    - echo "Start test 2"
  # this job is only added for pipelines NOT on the default branch
  rules:
    - if $CI_COMMIT_REF_NAME != $CI_DEFAULT_BRANCH
      when: on_success
    - when: never

Deploy_job:
  stage: deploy
  script:
    - echo "Start deploying the job"
  when: manual
    needs:
      - job: Test_job1
        optional: true
      - job: Test_job2
        optional: true

手动路径

如果在触发测试作业时仍需要人工参与,您可以将when:manual 换回when:on_success

真正的手动路径

或者,如果你真的只是想让你的人手动做出 Test_job: 临时决定,那么只需从 Deploy_job: 中删除 needs: 关键字并使用现有的 Stage 依赖结构。 when: manual 键隐式设置allow_failure: true,因此您的作业已经是可选的。如果您的人员无法通过手动作业自行管理“部署前测试”依赖项,那么请让人员脱离循环并查看上面的“自动化路径”。

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 2018-12-24
    • 2012-12-15
    • 2021-10-19
    • 2018-09-20
    • 2022-01-27
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    相关资源
    最近更新 更多