How to Deploy per Branch by Mapping Branch to Environment
Mapping branch to environment lets one workflow deploy each branch to its own target based on github.ref.
Deploy jobs read the branch from github.ref_name and pick an environment. Pair this with GitHub Environments for scoped secrets and approvals. Develop goes to staging, main goes to production, and feature branches optionally get preview environments.
Steps
- Run a deploy job on push to the branches you deploy from.
- Select the environment from
github.ref_name. - Attach a GitHub Environment so secrets and approvals are scoped per target.
- Fail closed if the branch has no mapped environment.
Workflow
.github/workflows/deploy.yml
on:
push:
branches: [develop, main]
jobs:
deploy:
runs-on: ubuntu-latest
environment: ${{ github.ref_name == 'main' && 'production' || 'staging' }}
steps:
- uses: actions/checkout@v4
- run: ./deploy.sh ${{ github.ref_name == 'main' && 'production' || 'staging' }}
env:
DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}Gotchas
- Scope production secrets to the production Environment so staging jobs cannot read them.
- A typo in the branch-to-env mapping can deploy staging code to production; assert it.
Related guides
How to Set CI Triggers per Branch With Push and PR FiltersControl which branches run CI using on.push.branches and on.pull_request.branches filters, so feature, develo…
How to Create Preview Environments for Feature BranchesSpin up a per-branch preview environment on each pull request and tear it down on close, so reviewers test fe…
How to Promote a Build Through Environments by BranchPromote the same tested artifact from staging to production by merging between environment branches, avoiding…