CoursesOpenTofuIntermediate

Workspaces & environments

dev, staging, prod from one codebase.

Intermediate10 min · lesson 8 of 12

You rarely manage just one environment. The two common patterns are the same as Terraform: workspaces, which keep multiple named states for one configuration, and directory-per-environment, which gives each environment its own directory and backend key. Workspaces are quick; separate directories are clearer and safer for very different or high-blast-radius environments like production.

TWO WAYS TO SPLIT ENVIRONMENTS
Workspaces
One config + one backend
shared, not duplicated
Multiple named states
default / staging / prod
Reference terraform.workspace
vary by variable
Best for identical envs
quick, differ only by vars
Directory per environment
Own directory + backend key
per environment
Fully separate state & settings
isolated
Best for divergent / prod
different accounts, sizing, guardrails
Clearer, harder to fat-finger
lower blast radius
Workspaces are quick for structurally-identical envs; separate directories are safer when environments truly diverge.
terminal
$ tofu workspace new staging
$ tofu workspace new prod
$ tofu workspace select prod
$ tofu workspace list
default
staging
* prod
# reference the current workspace in config:
# bucket = "acme-${terraform.workspace}-data"

Choosing a pattern

Workspaces share one backend and one configuration, so they suit environments that are structurally identical and differ only by variables. When environments diverge — different accounts, different sizing, production needing extra guardrails — a directory (or a Terragrunt layout) per environment keeps their state and settings fully separate, which is easier to reason about and harder to fat-finger across.

Do not use the default workspace for prod
It is easy to run an apply in the wrong workspace and hit production by accident — the default workspace is the classic trap. Name your environments explicitly, echo terraform.workspace in CI before applying, and gate the prod workspace behind approval so a mis-selected workspace cannot silently change prod.