在Github Action中的If Else

5

我在关注这个。

https://github.community/t/github-actions-manual-trigger-approvals/16233/83

  - name: Clone Repository (Latest)
    uses: actions/checkout@v2
    if: github.event.inputs.git-ref == ''
  - name: Clone Repository (Custom Ref)
    uses: actions/checkout@v2
    if: github.event.inputs.git-ref != ''
    with:
      ref: ${{ github.event.inputs.git-ref }}

这个方法虽然有效,但多步骤会使工作流程变得更加复杂。

我正在尝试更紧凑的方法,比如在环境变量中确定提交的 SHA。

env:
  COMMIT_HASH: ${{ github.event.inputs.git-ref != '' && github.event.inputs.git-ref || github.sha }}

这个方法可以正常工作,但是对我来说看起来像是一个丑陋的 hack。 有什么建议吗?我想尽量避免额外的步骤。

1个回答

3
您可以考虑使用haya14busa/action-cond操作。

当需要进行if-else操作以设置其他步骤的动态配置时,它非常有用(不需要复制整个步骤以在少数参数中设置不同的值)。

示例:

- name: Determine Checkout Depth
  uses: haya14busa/action-cond@v1
  id: fetchDepth
  with:
    cond: ${{ condition }}
    if_true: '0'  # string value
    if_false: '1' # string value
- name: Checkout
  uses: actions/checkout@v2
  with:
    fetch-depth: ${{ steps.fetchDepth.outputs.value }}

或者
steps:
- uses: haya14busa/action-cond@v1
  id: condval
  with:
    cond: ${{ github.event_name == 'pull_request' }}
    if_true: "value for pull request event"
    if_false: "value for non pull request event"
- name: Use conditional value
  run: echo "${{ steps.condval.outputs.value }}"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接