即使上一步失败,但作业仍然失败,如何运行下一个 github 操作步骤?

2024-03-20

这个问题类似于即使上一步失败,如何运行 github-actions 步骤,同时作业仍然失败 https://stackoverflow.com/questions/58858429/how-to-run-a-github-actions-step-even-if-the-previous-step-fails-while-still-f但接受的答案对我没有帮助,因为它创造了额外的工作。

我想在下面完成的是

  • 当测试应用程序(步骤2)通过时; test-clean 步骤应该运行并且 github 操作工作流返回成功。
  • 当测试应用程序(步骤2)失败时;应运行 test-clean、action-slack 和 failure-action 步骤。 github 操作工作流程返回失败。

如何修复以下代码以使其发生?

name: CI
on:
  pull_request:
    branches:
    - master
  push:
    branches:
      - master

jobs:
  build-and-test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v1    

    - name: test-app
      run: ./gradlew test

    - name: test-clean
      run: some cleanup that should run always

    - name: action-slack
      if: ${{ step2.result != 'success' }}
      uses: 8398a7/action-slack@v3
      with:
          status: ${{ step2.result }}
          fields: repo,message,commit,author,action,eventName,ref,workflow,job,took
      env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}

    - name: fail-action        
      run:  |
         if ${{ step2.result != 'success' }}; then
            exit 1
         fi


您可以使用状态检查功能 https://docs.github.com/en/actions/learn-github-actions/expressions#status-check-functions了解之前步骤的状态。如果你不包含这样的功能,if: success() && ...是暗示的。这意味着当之前的作业失败时,作业将不会运行,除非您使用always() or failure() in the if clause.

要解决前面步骤的结果,您可以使用steps context https://docs.github.com/en/actions/learn-github-actions/contexts#steps-context like steps.<id>.outcome(前continue-on-error已应用)或steps.<id>.conclusion (after continue-on-error被申请;被应用)。

这是一个结合了所有内容的工作示例:

jobs:
  build-and-test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2

    # Mock to test workflow
    - name: Test app
      id: test-app # will be referenced later
      run: |
        echo "Testing app (randomly fails)"
        if [[ $(($RANDOM % 2)) == 0 ]]; then exit 0; else exit 1; fi

    # runs always
    - name: test-clean
      if: always()
      run: echo "Cleanup after tests"

    # runs if previous jobs failed and test-app was not successful (failure/cancelled)
    - name: action-slack
      if: failure() && steps.test-app.outcome != 'success'
      run: |
        echo "Run action-slack"
        echo "Result of test-app was '${{ steps.test-app.outcome }}'"

PS: The answer in the other question does not add an additional job but includes an example on how to apply it across jobs. However, that answer does not address your exact use case but it could have helped you by giving some pointers.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

即使上一步失败,但作业仍然失败,如何运行下一个 github 操作步骤? 的相关文章

随机推荐