如何阻止GitHub Actions中Pull Request工作流重复执行(特殊场景)
解决方案
你的问题根源在于PR合并到development分支时,会同时触发push事件(合并提交推送到分支)和pull_request closed事件,导致工作流重复执行;同时你之前的条件写法虽然能过滤未合并的PR关闭事件,但没解决重复触发的问题。
以下是修正后的工作流配置,既保证仅在需要的场景执行任务,又避免重复触发:
# Controls when the workflow will run on: push: branches: ["development"] pull_request: branches: ["development"] types: - closed # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: # This workflow contains a single job called "build" build: # The type of runner that the job will run on runs-on: self-hosted # 条件逻辑: # 1. 若是push事件,排除PR合并产生的提交(避免和PR合并事件重复) # 2. 若是pull_request事件,仅在PR已合并时执行 if: > (github.event_name == 'push' && !contains(github.event.head_commit.message, 'Merge pull request')) || (github.event_name == 'pull_request' && github.event.pull_request.merged == true) # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v3 with: clean: false # 后续步骤...
关键说明
- 排除PR合并的push事件:PR合并产生的提交消息默认包含
Merge pull request,通过!contains(...)过滤这类push,避免和PR合并触发的工作流重复执行 - PR仅合并时执行:保留
pull_request closed触发类型,但通过github.event.pull_request.merged == true确保只有合并成功的PR才会执行任务 - 兼容手动触发:
workflow_dispatch不受条件影响,依然可以手动运行工作流
内容的提问来源于stack exchange,提问作者apes-together-strong
相关产品推荐
相关产品推荐

