You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何允许GitHub Actions在受保护分支上合并PR?

问题:如何让GitHub Actions机器人合并受保护分支的PR?

问题详情

  • 已配置仓库允许GitHub Actions批准PR(截图:GitHub Actions批准PR配置)
  • 已设置受保护分支规则,要求合并前需1个批准(截图:受保护分支批准要求)
  • 执行以下GitHub Actions步骤时,PR成功批准但合并失败:
- name: perform the merge if applicable
  env:
    GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  shell: bash
  run: |
      echo "Approving PR..."
      gh pr review --approve ${{ github.event.issue.number }}
      echo "Merging PR..."
      gh pr merge ${{ github.event.issue.number }} --admin --squash

初始报错信息

Approving PR...
Merging PR...
Message: You're not authorized to push to this branch. Visit https://docs.github.com/articles/about-protected-branches/ for more information., Locations: [{Line:1 Column:58}]

更新1:移除--admin参数后的报错

Approving PR...
Merging PR...
X Pull request #199 is not mergeable: the base branch policy prohibits the merge.
To have the pull request merged after all the requirements have been met, add the `--auto` flag.
To use administrator privileges to immediately merge the pull request, add the `--admin` flag.

更新2:添加令牌权限后仍无效

已为GITHUB_ACTIONS令牌配置以下权限,但问题未解决:

permissions:
 contents: write
 pull-requests: write
 repository-projects: write

解决方案

1. 配置受保护分支的绕过权限

进入仓库的「Settings」→「Branches」,找到目标受保护分支的规则并编辑:

  • 找到「允许指定角色或人员绕过拉取请求要求」选项
  • 添加github-actions[bot]账号到允许列表,保存设置

2. 调整Actions合并命令

移除--admin参数,改用--auto参数,让Actions等待所有合并条件满足后自动执行合并。修改后的步骤代码:

- name: perform the merge if applicable
  env:
    GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  shell: bash
  run: |
      echo "Approving PR..."
      gh pr review --approve ${{ github.event.issue.number }}
      echo "Merging PR..."
      gh pr merge ${{ github.event.issue.number }} --auto --squash

3. 确认令牌权限配置

确保Actions的权限配置至少包含以下内容(你当前的配置已满足,无需额外修改):

permissions:
  contents: write
  pull-requests: write

内容的提问来源于stack exchange,提问作者pkaramol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:50:26