Managing Multiple Environments in Terraform
Almost every project needs the same infrastructure in several environments, with small differences: smaller instances in dev, more replicas in prod. There are three common approaches.
1. Separate directories (most common)
infra/
modules/
app/ # the shared building blocks
envs/
dev/
main.tf # module "app" { source = "../../modules/app", size = "small" }
backend.tf # its own state key
staging/
prod/
- Each environment has its own state, backend and provider settings.
- Differences are explicit and reviewable.
- You can upgrade a module version in dev first, then promote it.
- Some repetition between folders, kept small by putting logic in modules.
2. Workspaces
terraform workspace new staging
terraform workspace select staging
terraform apply -var-file=staging.tfvars
locals {
instance_count = terraform.workspace == "prod" ? 4 : 1
}
- One configuration, multiple states.
- Easy to forget which workspace you're in and apply to the wrong one.
- All environments share the same backend and credentials, which is weak isolation for production.
- Good for short-lived copies (feature environments), less so for prod.
3. One config plus tfvars per environment
terraform init -backend-config=backends/prod.hcl
terraform apply -var-file=envs/prod.tfvars
Works well when environments are nearly identical, but requires discipline in CI to always pass matching backend and variable files.
Recommendations
- Use separate cloud accounts or projects per environment, with separate credentials.
- Prefer separate directories with shared modules for long-lived environments.
- Run plans and applies from CI, not laptops, so the environment selection is automated.
- Tools like Terragrunt can reduce duplication when you have many environments and regions.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.