Skip to content
Latchkey

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

Run this faster and cheaper on Latchkey managed runners. Start free →