How can I protect a GitHub branch and allow only GitHub actions to push to it and no one else?

1.8k Views Asked by At

I am writing a GitHub workflow where I am building documentation from the main branch docstrings and pushing it to gh-pages and having GitHub pages deploy off of gh-pages branch. How can I protect that branch so that only GitHub branches can push to it and not allow anyone else?

2

There are 2 best solutions below

1
On

A new branch protection rule can be set up at https://github.com/USERNAME/REPO/settings/branch_protection_rules/new. Any branch that has a matching name will be protected. The option "lock branch" will lock the branch and only allow admins to override and commit. Additionally, branch protection rules should be set up on main to require a pull request that way people cannot just push directly to main.

0
On

I facing exactly the same use case in my repo,

after read the issue in the GitHub community, here comes my workaround as follow:

  • Set two branch rules
    1. main : check "Require a pull request before merging" and "Require 1 approvals"
    2. gh-pages: check "Allow force pushes" and add yourself or an org-account to the "Specify who can force push"
  • create a PAT of yourself or the org-account and save to repository secret (In Setting/Actions secrets and variables/Actions)
  • add with token when checkout code in GHA:
    steps:
       - uses: actions/checkout@v3
         with:
           token: ${{ secrets.GH_TOKEN}}
    
  • in Settings/Actions permissions/Fork pull request workflows from outside collaborators, check
    • "require approval for first-time contributors" or
    • "require approval for all outside collaborators"