GitHub CLI – Programmatically Disabling and Enabling Branch Protection Rules

Today I needed to be able to automatically disable and enable branch protection rules on a GitHub repository so that an Actions Build Template could be added to the main/master branch.

There is this known reported issue that despite adding a GitHub Actions Workflow file – unless it’s on the main/master branch – you can’t use the workflow_dispatch popup on the UI so build can be manually triggered (if needed).

So I did some investigation and created an automation to copy a workflow to the main/master branch.

In the process I uncovered that some repositories weren’t setup properly with their branch protection rules which blocked the automation.

As a result, I studied the GitHub API and wrote up the below snippet to allow temporary disable/enable of branch protection.

#!/bin/bash

# Get command-line arguments
owner="$1"
target_repo="$2"
target_branch="$3"

echo "Disabling Branch Protection Rules for $target_branch on $target_repo"

gh api repos/$owner/$target_repo/branches/$target_branch/protection \
  -H "Accept: application/vnd.github.v3+json" \
  -X DELETE || echo "Branch protection rules already disabled or don't exist"

echo "Enabling Branch Protection Rules for $target_branch on $target_repo"

PAYLOAD='{
    "required_status_checks": null,
    "enforce_admins": true,
    "required_pull_request_reviews": {
        "dismissal_restrictions": {
            "users": [],
            "teams": ["my_team_name"]
        },
        "dismiss_stale_reviews": false,
        "require_code_owner_reviews": false,
        "required_approving_review_count": 1,
        "require_last_push_approval": false,
        "bypass_pull_request_allowances": {
            "users": ["my_service_account_user_id"],
            "teams": []
        }
    },
    "restrictions": {
        "users": [],
        "teams": ["my_team_name"],
        "apps": []
    },
    "required_linear_history": false,
    "allow_force_pushes": false,
    "allow_deletions": false,
    "block_creations": true,
    "required_conversation_resolution": true,
    "lock_branch": false,
    "allow_fork_syncing": true
}'

echo "$PAYLOAD" | gh api repos/$owner/$target_repo/branches/$target_branch/protection \
  -H "Accept: application/vnd.github.v3+json" \
  -X PUT \
  --silent \
  --input - || (echo "Failed to enable branch protection rules for $target_branch on $target_repo" && exit 1)

Leave a comment