如何在两个GitHub Action工作流均完成后触发第三个deploy工作流
当前配置的workflow_run触发器规则为:监听列表内任意工作流完成即触发,因此后端构建、前端构建各自执行完成后都会触发一次deploy工作流,自然会重复执行两次。
方案一:合并为同一工作流(推荐)
将构建、部署逻辑放在同一个工作流文件中,通过needs字段声明任务依赖,只有所有前置任务全部执行成功时,才会执行后续部署任务,配置简洁且不易出错。
# .github/workflows/build-deploy.yml name: Build and Deploy on: push: branches: - master pull_request: branches: - master jobs: build_backend: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 # 原后端构建的其他步骤... build_frontend: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 # 原前端构建的其他步骤... deploy: runs-on: ubuntu-latest # 明确指定依赖两个构建任务,两个都成功才会执行deploy needs: [build_backend, build_frontend] steps: # 原部署的步骤...
方案二:保留独立工作流,增加状态校验
如果必须拆分三个工作流为独立文件,可以在deploy工作流的执行逻辑前增加校验步骤,查询当前提交对应的两个前置构建工作流是否均已执行成功,仅校验通过时才继续执行部署。
# .github/workflows/deploy.yml name: Deploy on: workflow_run: workflows: - "Build and Test - Backend" - "Build and Test - Frontend" types: - completed branch: master jobs: deploy: runs-on: ubuntu-latest if: ${{ github.event.workflow_run.conclusion == 'success' }} steps: - name: Checkout uses: actions/checkout@v4 - name: 校验两个构建任务均已成功 id: check_builds uses: actions/github-script@v7 with: script: | const commitSha = '${{ github.event.workflow_run.head_sha }}'; // 查询当前commit下两个构建工作流的执行状态 const { data: runs } = await github.rest.actions.listWorkflowRunsForRepo({ owner: context.repo.owner, repo: context.repo.repo, head_sha: commitSha, status: 'success' }); const backendSuccess = runs.workflow_runs.some(run => run.name === 'Build and Test - Backend'); const frontendSuccess = runs.workflow_runs.some(run => run.name === 'Build and Test - Frontend'); return backendSuccess && frontendSuccess; - name: 执行部署 if: steps.check_builds.outputs.result == 'true' run: | # 你的部署脚本
内容的提问来源于stack exchange,提问作者marqueewinq
相关产品推荐
相关产品推荐

