Terraform 31: 4: Workspaces vs directories — the trade-offs
easy⏱ 5 mincourseterraform
Workspaces: one dir, many states
A workspace lets one directory hold multiple named state files. You switch with terraform workspace select prod and branch on terraform.workspace inside the config. Fast to set up, but all environments share the exact same code with no room to diverge.
# One directory, switched by workspace name
terraform workspace new dev
terraform workspace new prod
terraform workspace select prod
locals {
# per-workspace sizing, keyed by terraform.workspace
vm_count = {
dev = 1
prod = 3
}[terraform.workspace]
}
Directories: one dir per environment
The directory-per-environment approach (Lesson 6.2) gives each environment its own folder, backend key, and tfvars. More files to keep in sync, but each environment is explicit, independently reviewable, and free to diverge (prod can add a resource dev lacks).
# Directory-per-environment: explicit, independent
# envs/dev -> its own backend key + tfvars
# envs/prod -> its own backend key + tfvars
cd envs/prod && terraform init && terraform apply
When to pick which
Use workspaces for many near-identical, short-lived, low-risk copies (per-developer sandboxes, ephemeral PR previews). Use directories for the dev/uat/prod promotion path — the environments differ, prod is high-risk, and a single flat .tf file visible in a PR is safer than a hidden terraform.workspace switch.
The workspace foot-gun
With workspaces it is easy to forget which one is selected and apply prod changes while pointed at prod thinking you were in dev. Directories make the target unmistakable — you are literally cd'd into envs/prod. That explicitness is why most teams prefer directories for prod.
Recommend an approach
Write recommend(scenario) that returns "workspaces" when scenario is "ephemeral" or "sandbox", and "directories" otherwise (e.g. "prod"). Log recommend("prod") — it must print directories.