Branch-based Development

Preview infrastructure changes per branch using Projen-generated tasks and workflows.


Overview

Branch-based deployments let every feature branch spin up its own copy of the stacks so you can test infrastructure changes without touching shared environments. This guide covers how to enable the workflow, deploy locally, and understand the cleanup process.

Enable branch deploys in .projenrc.ts

Set enableBranchDeploy: true on any environment inside environmentConfigs (see Configuration > Environments). After running npx projen, the starter kit generates:

  • npm tasks such as npm run test:branch:deploy:all and npm run test:branch:diff:stack.
  • GitHub Actions workflows named cdk-deploy-<env>-branch and cdk-destroy-<env>-branch.

These tasks use helpers from env-helper.ts to inject GIT_BRANCH_REF and to clean branch names safely (extractCleanedBranchName). Stack and resource IDs are suffixed via createEnvResourceName so they stay unique per branch.

Local workflow

# create a feature branch
git checkout -b feature/payment-alerts
 
# preview CloudFormation output
npm run test:branch:synth
npm run test:branch:diff:stack StarterStack
 
# deploy stacks with branch suffixes
npm run test:branch:deploy:stack StarterStack
 
# tear down once finished
npm run test:branch:destroy:stack StarterStack

The tasks automatically set GIT_BRANCH_REF using your current git branch. For day-to-day commands like build and lint, follow the Local Development guide.

GitHub Actions workflow

When you push the branch, the generated workflow:

  1. Calculates a safe branch identifier using extractCleanedBranchName.
  2. Runs synth and deploy using branch tasks so stack names include the suffix (for example, StarterStack-feature-payment-alerts).
  3. Tags resources with both the environment and branch labels (handled in src/main.ts).
  4. Cleans up automatically when the PR closes or the branch is deleted (cdk-destroy-<env>-branch). Manual cleanup is available through the workflow dispatch event as well.

Guardrails

  • Foundation stack exclusion: FoundationStack never deploys in branch mode, preventing temporary environments from tampering with shared IAM roles.
  • Main branch protection: createEnvResourceName throws if GIT_BRANCH_REF resolves to main, ensuring production stack names remain stable.
  • IAM trust policy: Ensure the GitHub OIDC role allows refs like repo:<owner>/<repo>:environment:<env> and, if needed, add conditions for refs/heads/feature/* in the IAM trust relationship.

Clean exits

Always destroy branch stacks when you finish:

npm run test:branch:destroy:all

Leaving stacks active can incur cost and delay subsequent deploys if resources collide. The destroy workflow is idempotent, so it is safe to run multiple times.

Ready to merge? The CI/CD Workflow guide explains how mainline deploys pick up once your branch lands.