Pull Request检测不到workflow_run触发的工作流运行状态如何解决
问题根因
workflow_run 触发的工作流默认运行在仓库默认分支的安全上下文,关联提交为默认分支最新提交,而非PR源分支的提交,因此其运行状态不会自动同步到PR的校验队列中。
解决方案1:手动上报状态到PR对应提交(无需调整现有触发逻辑)
只需要修改第二个工作流配置,补充参数获取、指定代码版本、手动上报状态的逻辑即可,修改后的配置如下:
name: Second on: workflow_run: workflows: ["First"] types: - completed jobs: golangci: if: ${{ github.event.workflow_run.conclusion == 'success' }} name: lint runs-on: ubuntu-latest # 添加上报状态需要的权限 permissions: statuses: write actions: read contents: read steps: # 检出PR对应提交的代码,而非默认分支代码 - uses: actions/checkout@v3 with: ref: ${{ github.event.workflow_run.head_sha }} - name: golangci-lint id: lint uses: golangci/golangci-lint-action@v2 with: version: latest # 上报成功状态到PR的对应提交 - name: Report success status if: ${{ success() }} run: | curl -L \ -X POST \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \ https://api.github.com/repos/${{ github.repository }}/statuses/${{ github.event.workflow_run.head_sha }} \ -d '{"state":"success","context":"Second","description":"Lint check passed","target_url":"https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"}' # 上报失败状态到PR的对应提交 - name: Report failure status if: ${{ failure() }} run: | curl -L \ -X POST \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \ https://api.github.com/repos/${{ github.repository }}/statuses/${{ github.event.workflow_run.head_sha }} \ -d '{"state":"failure","context":"Second","description":"Lint check failed","target_url":"https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"}'
注意:配置中的
context字段值Second需要和分支保护规则中要求的检查名称完全一致,才能被PR规则识别。
解决方案2:改用可复用工作流(逻辑更简洁,无额外API调用)
将第二个工作流改造为可复用工作流,由第一个工作流运行完成后直接调用,此时第二个工作流会继承第一个工作流的PR上下文,状态会自动同步到PR校验队列,适配多工作流的大型仓库场景。
- 改造第二个工作流为可复用工作流,修改触发规则为
workflow_call:
# 保存为 .github/workflows/second-reusable.yml name: Second on: workflow_call: jobs: golangci: name: lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: golangci-lint uses: golangci/golangci-lint-action@v2 with: version: latest
- 修改第一个工作流,测试任务完成后调用第二个可复用工作流:
name: First on: pull_request: branches: [ master ] jobs: test: name: test runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.16 - name: Test run: go test -v ./... # 新增调用第二个工作流的任务 call-second-workflow: needs: test uses: ./.github/workflows/second-reusable.yml
该方案完全不需要手动处理状态同步,后续新增工作流只需要按照可复用规范改造即可。
内容的提问来源于stack exchange,提问作者pigfrown
相关产品推荐
相关产品推荐

