【问题标题】:Conditional "needs" in GitHub Action?GitHub Action 中的条件“需求”?
【发布时间】:2021-09-20 18:21:30
【问题描述】:

我有一个(简化的)GitHub 工作流程,如下所示:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: echo "build"

  test:
    runs-on: ubuntu-latest
    needs: build

    steps:
      - run: echo "build"

  deploy:
    runs-on: ubuntu-latest
    needs: [build, test]

    steps:
      - run: echo "deploy"

现在,如果分支是main,我想使deploy 步骤只需要tests 步骤。

这可能吗?

基本上我很想做这样的事情:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: echo "build"

  test:
    runs-on: ubuntu-latest
    needs: build

    steps:
      - run: echo "build"

  deploy:
    runs-on: ubuntu-latest
    needs: contains(branch, "master") ? [build, test] : [build] #notice this line

    steps:
      - run: echo "deploy"

【问题讨论】:

  • 例如${{ (contains(branch, "master") && [build, test]) || [build] }} 工作? github.community/t/… 有一些条件表达式选项

标签: github-actions


【解决方案1】:

GitHub 操作不允许有条件的需求(不幸的是,恕我直言)。

然而,有一个解决方法: 通过在needs 中定义先决条件,使您的作业按顺序运行。无论先决条件发生了什么,所有需要运行的作业都需要将if 条件设置为always()。

如果之前的作业失败应该会导致您需要添加一个步骤来验证作业结果。

这是一个通用的适配方案:

jobs:
  init_job:
    runs-on: ubuntu-latest
    steps:
      - run: echo "initial run"

  conditional_job:
    runs-on: ubuntu-latest
    needs: init_job
    if: ${{ your condition here }}
    steps:
      - run: echo "conditonal run"

  final_job:
    needs: conditional_job
    if: always()
    steps:
      - name: fail if conditional job failed
        if: ${{ needs.conditional_job.result == 'failure' }}
        run: exit 1
      - run: echo "final run"

【讨论】:

  • 聚合needs中的多个条件作业,步骤条件可以是if: ${{ contains(needs.*.result, 'failure') }}
【解决方案2】:

不理想,但你可以使用这个:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: echo "build"

  test:
    runs-on: ubuntu-latest
    needs: build

    steps:
      - run: echo "build"

  deploy-main:
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    needs: [build, test]

    steps:
      - run: echo "deploy"
        
  deploy:
    runs-on: ubuntu-latest
    if: github.ref != 'refs/heads/main'
    needs: build

    steps:
      - run: echo "deploy"

【讨论】:

  • 问题是部署步骤真的很长而且很复杂,所以很遗憾目前对我没有用。
  • 你可以考虑composite actions避免重复自己
  • 另外请检查topic 恐怕您将无法在needs 范围内使用github 或env 上下文。当我使用它时,我得到了Unrecognized named-value: 'env'
  • 嗯,通过复合动作,我可以在本地拥有它们吗?还是需要将它们托管在单独的存储库中?
  • 您可以将它们放在同一个仓库中。请查看here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 2021-08-24
  • 2021-08-28
  • 2020-07-12
  • 2023-01-26
  • 2022-08-10
  • 2021-10-26
相关资源
最近更新 更多