CI/CD and automation · Intermediate · 18 min
Require approval before production deploys with GitHub environments
By Padding · Updated 18 Nov 2026
GitHub Actions · GitHub CLI 2.106.0 · actionlint 1.7.12 · Ubuntu 26.04
You will have a GitHub Actions workflow that deploys every push to main to staging on its own, then holds the production deploy until a named reviewer approves it, with each environment's secrets, allowed branches and live URL set up from the GitHub CLI.
On this page
A workflow that deploys on every push is fast, and it means one bad merge reaches your users before anyone looks at it. GitHub environments put a gate between the two. A job that names an environment picks up that environment's rules: who must approve it, how long to wait, which branches and tags are allowed to deploy, and which secrets it can read. Until the rules pass, the job waits and its secrets stay out of reach.
You will set up two environments. staging has no gate: every push to main deploys there. production needs one approval from a reviewer you name, holds every run for five minutes so a mistake can still be cancelled, and accepts only main and tags such as v1.4.0. Both get their own deploy token and URL, so a staging job can never read the production token. All the settings are made with gh api, so you can keep them in the repository and repeat them on the next project.
Which plan you need
For a public repository every feature here works on every GitHub plan. For a private repository, GitHub's documentation (checked 26 November 2026) says:
- Required reviewers and wait timers: only on GitHub Enterprise. On Free, Pro and Team they work in public repositories only.
- Deployment branch and tag rules, and environment variables: Pro, Team or Enterprise.
- Environment secrets: Pro, Team or Enterprise (on Free, public repositories only).
If your private repository is on Team, you can still scope secrets and branches as below; the approval gate itself will not apply. Check the current table at docs.github.com/en/actions/reference/workflows-and-actions/deployments-and-environments before you rely on it.
Step 1 · Create staging and choose who approves production
Run everything from the root of your repository clone. Set two shell variables first: your repository, and the GitHub login of the person who will approve production deploys. Replace both values:
REPO=your-org/your-repo
REVIEWER_LOGIN=their-github-loginCreate staging with no rules. A PUT with no body creates the environment, or leaves an existing one as it is:
gh api --method PUT "repos/$REPO/environments/staging"The REST API wants reviewers as numeric IDs, not logins. Look the ID up:
REVIEWER_ID="$(gh api "users/$REVIEWER_LOGIN" --jq .id)"
echo "$REVIEWER_ID"For a whole team, use gh api orgs/ORG/teams/TEAM-SLUG --jq .id and the type Team in the next step. A team is the better choice when people go on leave or work across time zones: any one member can approve, so a release is not stuck because the only reviewer is offline, travelling or out of mobile data.
Check it worked
gh api "repos/$REPO/environments" --jq '.environments[].name' lists staging, and echo "$REVIEWER_ID" printed a number such as 583231, not an error.
Step 2 · Write the production rules as a file
Keep the production settings in a JSON file, so the gate is reviewed in pull requests like any other code. jq -n builds it, which inserts the reviewer ID as a number and keeps the file valid:
mkdir -p .github/environments
jq -n --argjson id "$REVIEWER_ID" '{
wait_timer: 5,
prevent_self_review: true,
reviewers: [ { type: "User", id: $id } ],
deployment_branch_policy: {
protected_branches: false,
custom_branch_policies: true
}
}' > .github/environments/production.json
cat .github/environments/production.jsonWhat each field does:
wait_timer: 5delays the job five minutes after it is triggered. GitHub accepts 0 to 43,200 minutes (30 days). It gives you a window to cancel a run you regret.reviewerslists up to six users or teams. They need at least read access to the repository, and one approval is enough.prevent_self_review: truestops the person who triggered the run from approving it, so every production deploy has a second pair of eyes. If you are the only maintainer, set it tofalse, or you will never be able to approve your own deploys.deployment_branch_policywithcustom_branch_policies: truemeans only the branch and tag names you list in a later step may deploy. The two booleans must be opposites; GitHub rejects the request if both aretrueor bothfalse.
Check it worked
Ask jq to confirm the values you meant to set:
jq -e '.wait_timer == 5 and .prevent_self_review == true and (.reviewers | length) == 1 and (.reviewers[0].id | type) == "number"' .github/environments/production.jsonIt prints true. A false, or an error, means the file does not hold what you expect; open it and compare it with the block above.
Step 3 · Apply the rules and restrict deploy branches and tags
Send the file to GitHub. The same command updates the environment whenever you change the file:
gh api --method PUT "repos/$REPO/environments/production" --input .github/environments/production.jsonNow add the names that may deploy: the main branch, and tags that start with v. Patterns follow Ruby's File.fnmatch, and a wildcard does not match /, so v* matches v1.4.0 but not v1/hotfix:
gh api --method POST "repos/$REPO/environments/production/deployment-branch-policies" -f name=main -f type=branch
gh api --method POST "repos/$REPO/environments/production/deployment-branch-policies" -f name='v*' -f type=tagOne setting is not in the REST API: by default, repository administrators can bypass the protection rules. Open the repository's Settings, then Environments, then production, and untick "Allow administrators to bypass configured protection rules" if admins should wait for approval too.
Check it worked
Read the settings back:
gh api "repos/$REPO/environments/production" --jq '.protection_rules[].type'
gh api "repos/$REPO/environments/production/deployment-branch-policies" --jq '.branch_policies[] | "\(.type) \(.name)"'The first command lists rule types, something like required_reviewers, wait_timer and branch_policy. The second prints branch main and tag v*. If required_reviewers is missing on a private repository, your plan does not include it (see the plan table above).
Step 4 · Give each environment its own token and URL
Store the deploy token as a secret in each environment, with a different token for each. Your host's dashboard issues these; make a separate one for staging and production, so a leaked staging token cannot touch production. Without --body, gh secret set prompts for the value, which keeps it out of your shell history:
gh secret set DEPLOY_TOKEN --env staging --repo "$REPO"
gh secret set DEPLOY_TOKEN --env production --repo "$REPO"The hook URL and the public site URL are not secret, so they are variables. Replace the example addresses with your own:
gh variable set DEPLOY_HOOK_URL --env staging --repo "$REPO" --body "https://deploy.example.com/hooks/staging"
gh variable set SITE_URL --env staging --repo "$REPO" --body "https://staging.example.com"
gh variable set DEPLOY_HOOK_URL --env production --repo "$REPO" --body "https://deploy.example.com/hooks/production"
gh variable set SITE_URL --env production --repo "$REPO" --body "https://www.example.com"Both environments use the same names, DEPLOY_TOKEN, DEPLOY_HOOK_URL and SITE_URL. The job's environment decides which values it gets, so the deploy steps can be identical. A job sees an environment's secrets and variables only if it names that environment, and a job waiting for approval cannot read the secrets until a reviewer approves it.
Do not also create a repository-level secret called DEPLOY_TOKEN. An environment secret wins over one with the same name, but a job that forgets its environment: line would then quietly get the repository one.
Check it worked
gh secret list --env production --repo "$REPO"
gh variable list --env production --repo "$REPO"The first lists DEPLOY_TOKEN with the time it was updated (never its value). The second lists DEPLOY_HOOK_URL and SITE_URL with the production addresses. Run the same two commands with --env staging and check you see the staging addresses.
Step 5 · Write the deploy script and try it locally
The workflow calls one script for both environments. It reads everything from environment variables, sends the token to the hook, and writes the site URL to GITHUB_OUTPUT so the run can show it. The token goes to curl through standard input (--config -) rather than as a command-line argument, so it never appears in the runner's process list:
mkdir -p scripts
cat > scripts/deploy.sh <<'SCRIPT'
#!/usr/bin/env bash
set -euo pipefail
: "${DEPLOY_HOOK_URL:?DEPLOY_HOOK_URL is not set}"
: "${DEPLOY_TOKEN:?DEPLOY_TOKEN is not set}"
: "${SITE_URL:?SITE_URL is not set}"
ref="${GITHUB_SHA:-local}"
printf 'header = "Authorization: Bearer %s"\n' "$DEPLOY_TOKEN" |
curl --config - --fail-with-body -sS -X POST \
-H "Content-Type: application/json" \
--data "{\"ref\":\"$ref\"}" \
"$DEPLOY_HOOK_URL"
echo
if [ -n "${GITHUB_OUTPUT:-}" ]; then
echo "url=$SITE_URL" >> "$GITHUB_OUTPUT"
fi
echo "Deployed $ref to $SITE_URL"
SCRIPTBefore trusting it in CI, run it against a small listener on your computer that plays the part of your host's hook. It accepts a POST only when the bearer token matches the one it was started with:
cat > mock_hook.py <<'PY'
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
EXPECTED = "Bearer " + os.environ["DEPLOY_TOKEN"]
class Hook(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
body = json.loads(self.rfile.read(length) or b"{}")
ok = self.headers.get("Authorization") == EXPECTED
self.send_response(200 if ok else 401)
self.send_header("Content-Type", "application/json")
self.end_headers()
reply = {"status": "queued", "ref": body.get("ref")} if ok else {"error": "bad token"}
self.wfile.write(json.dumps(reply).encode())
def log_message(self, *args):
pass
HTTPServer(("127.0.0.1", 8471), Hook).serve_forever()
PYType any practice token when read waits (the text stays hidden). Use a made-up value, not a real deploy token:
read -rs DEPLOY_TOKEN
export DEPLOY_TOKENStart the listener in the background, wait until it answers, and point the script at it:
python3 mock_hook.py &
HOOK_PID=$!
for i in $(seq 1 20); do curl -s -o /dev/null http://127.0.0.1:8471/ && break; sleep 0.5; done
export DEPLOY_HOOK_URL=http://127.0.0.1:8471/deploy
export SITE_URL=https://staging.example.com
export GITHUB_OUTPUT="$PWD/deploy-output.txt"
bash scripts/deploy.sh
cat deploy-output.txtCheck it worked
The script prints {"status": "queued", "ref": "local"}, then Deployed local to https://staging.example.com, and deploy-output.txt holds url=https://staging.example.com. Now prove a wrong token stops the deploy:
grep -qx 'url=https://staging.example.com' deploy-output.txt
DEPLOY_TOKEN=wrong-token bash scripts/deploy.sh || echo "deploy refused, exit status $?"You see {"error": "bad token"} and deploy refused, exit status 22: --fail-with-body makes curl fail on the 401, and set -e stops the script before it reports a deploy. Stop the listener and clear the practice values:
kill "$HOOK_PID"
wait "$HOOK_PID" 2>/dev/null || true
rm -f mock_hook.py deploy-output.txt
unset DEPLOY_TOKEN DEPLOY_HOOK_URL SITE_URL GITHUB_OUTPUTStep 6 · Write the two-stage workflow
Create .github/workflows/deploy.yml. Each job names its environment and takes its URL from the deploy step's output, so the run page links straight to the deployed site:
mkdir -p .github/workflows
cat > .github/workflows/deploy.yml <<'YAML'
name: Deploy
on:
push:
branches: [main]
tags: ['v*']
permissions:
contents: read
jobs:
staging:
runs-on: ubuntu-latest
environment:
name: staging
url: ${{ steps.deploy.outputs.url }}
concurrency:
group: deploy-staging
cancel-in-progress: false
steps:
- uses: actions/checkout@v7
- name: Deploy to staging
id: deploy
env:
DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
DEPLOY_HOOK_URL: ${{ vars.DEPLOY_HOOK_URL }}
SITE_URL: ${{ vars.SITE_URL }}
run: bash scripts/deploy.sh
production:
needs: staging
runs-on: ubuntu-latest
environment:
name: production
url: ${{ steps.deploy.outputs.url }}
concurrency:
group: deploy-production
cancel-in-progress: false
steps:
- uses: actions/checkout@v7
- name: Deploy to production
id: deploy
env:
DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
DEPLOY_HOOK_URL: ${{ vars.DEPLOY_HOOK_URL }}
SITE_URL: ${{ vars.SITE_URL }}
run: bash scripts/deploy.sh
YAMLHow the pieces fit:
needs: stagingmeans production starts only after staging succeeds. Then theproductionenvironment's rules apply: the branch or tag must match, the wait timer runs, and a reviewer must approve.- The two deploy steps are word for word the same.
secrets.DEPLOY_TOKENandvars.SITE_URLresolve to the staging or production values according to the job'senvironment:name. concurrencywithcancel-in-progress: falsequeues a second deploy to the same environment instead of running two at once or cancelling one that has started.- Secrets reach the script through
env:, never written inline inrun:, and the workflow token is read-only because the deploy uses the host's token, not GitHub's.
Lint the workflow with actionlint 1.7.12 (/tutorials/github-actions-first-workflow shows how to install it):
actionlint .github/workflows/deploy.yml
echo "actionlint exit code: $?"Check it worked
actionlint prints nothing, then actionlint exit code: 0. An error such as property "deploy" is not defined in object type {} means an id: deploy is missing from a deploy step, so the url: line has nothing to read.
Step 7 · Push, then approve the production deploy
Commit the script, the settings file and the workflow, and push to main:
git add scripts/deploy.sh .github/environments/production.json .github/workflows/deploy.yml
git commit -m "Deploy to staging automatically and to production after approval"
git push origin mainOpen the run in the Actions tab. staging runs at once and, when it finishes, shows the staging URL next to the job. production shows as waiting. Your reviewer gets a notification, opens the run, chooses Review deployments, ticks production, optionally writes a comment such as the ticket number, and chooses Approve and deploy. Reject fails the run, and nothing reaches production.
Try the rules from both sides:
- With
prevent_self_reviewon, the person who pushed sees the review button but cannot approve their own run. - To release from a tag, run
git tag v1.0.0andgit push origin v1.0.0; the same two jobs run, and thev*tag rule lets production through after approval.
Check it worked
After approval and the five-minute timer, the production job turns green and shows the production URL. Open Code, then Deployments in the repository (or the environment's page in Settings) to see a history of who deployed what to each environment and when.
Step 8 · Clean up
If you set this up only to learn, delete both environments. Deleting an environment also deletes its secrets, variables and protection rules. This removes the production gate, so do not run it on a repository that relies on it:
gh api --method DELETE "repos/$REPO/environments/production"
gh api --method DELETE "repos/$REPO/environments/staging"Then remove the files the tutorial added, and commit that change if you had pushed them:
rm -rf scripts/deploy.sh .github/environments .github/workflows/deploy.ymlRevoke the two deploy tokens in your host's dashboard as well, because deleting the GitHub secrets does not invalidate the tokens themselves.
Check it worked
gh api "repos/$REPO/environments" --jq '.environments[].name' no longer lists staging or production, and ls .github/workflows no longer shows deploy.yml.
Next steps
- Replace long-lived cloud keys in the production environment with short-lived credentials: /tutorials/deploy-to-aws-from-github-actions-with-oidc.
- Use the same gate in front of an SSH deploy to your own server: /tutorials/deploy-to-a-server-over-ssh-with-github-actions.
- Review which secrets, variables and token permissions each workflow gets: /tutorials/manage-secrets-and-permissions-in-github-actions.
Part of these paths
Related tutorials
- Run only the CI jobs a change needs with path filters and concurrencyYou will have GitHub Actions workflows that skip tests for documentation-only changes without blocking merges, cancel superseded pull request runs, queue deploys instead of cancelling them, and stop any job that runs too long.
- Run Python tests and linters in GitHub Actions with uvYou will have a GitHub Actions workflow that installs a Python project with uv from its lock file, fails on a stale uv.lock, runs Ruff and pytest with a coverage floor on two Python versions, caches uv's downloads and keeps the coverage report as an artifact.
- Publish an npm package from GitHub Actions with trusted publishing and provenanceYou will have a small npm package that GitHub Actions publishes on each version tag through npm trusted publishing, with no NPM_TOKEN secret and a provenance attestation on every release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials