Workspaces and Environments (dev/stage/prod patterns)
Learn Terraform workspaces and recommended environment isolation patterns. Includes examples and safe practices.
Terraform supports multiple ways to manage environments. Two common approaches:
- Separate state per environment (recommended in most teams)
- Terraform workspaces (a built-in way to vary state)
Learning outcomes
You’ll be able to:
- explain what workspaces are
- choose an environment isolation strategy
- avoid the most common workspace/state mistakes
1) Why environments matter
Environments isolate risk:
devchanges shouldn’t affectprod- credentials and policies differ
- you want reproducible, auditable changes per environment
2) Terraform workspaces (concept)
A Terraform workspace selects a separate state file. State name example:
- default workspace →
terraform.tfstate devworkspace →terraform.tfstate.d/dev
Basic commands:
# list workspaces
terraform workspace list
# create and switch
terraform workspace new dev
# switch
terraform workspace select dev
3) Using workspace in configuration
Workspaces expose their name via terraform.workspace.
Example:
locals {
env = terraform.workspace
}
resource "null_resource" "example" {
triggers = {
env = local.env
}
}
You would then use local.env to drive naming:
app-${local.env}-bucket
4) Recommended approach: separate backend keys per environment
Instead of workspaces, configure your remote backend so each environment has its own state file (key).
Conceptual example:
envs/dev/terraform.tfstateenvs/prod/terraform.tfstate
In practice, you implement this by parameterizing backend config (often through CLI or separate backend config files).
Why this is often preferred:
- clearer separation
- fewer surprises when switching workspaces
- easier to reason about what state you’re pointing at
5) Practical guidance
If you use workspaces
- keep naming based on
terraform.workspace - never accidentally run against the wrong workspace
- always use
terraform planafter switching
If you don’t use workspaces
- define environment variables for naming and configuration
- ensure backend keys differ per env
6) Cleanup reminder
If using workspaces, destroy in the correct workspace:
terraform workspace select dev
terraform destroy