Manage Multiple Environments with Terraform Workspaces
Workspaces let you run the same Terraform config against dev, staging, and prod with separate state files.
What
Terraform workspaces let you maintain separate state files for the same configuration. Each workspace has its own isolated state, so you can deploy identical infrastructure to multiple environments like dev, staging, and prod from a single codebase. The current workspace name is available via terraform.workspace.
Why It Matters
Without workspaces, you would need to duplicate your entire Terraform configuration for each environment or manually manage multiple state files. Workspaces give you clean environment separation with zero code duplication, and the terraform.workspace variable lets you adjust resource names, sizes, and counts per environment.
Example
# Create and switch between workspaces
terraform workspace new dev
terraform workspace new staging
terraform workspace new prod
terraform workspace select staging
terraform workspace list
# Use workspace name in configuration
resource "aws_instance" "web" {
ami = var.ami_id # Use a variable or data source for your region
instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro"
tags = {
Name = "web-${terraform.workspace}"
Environment = terraform.workspace
}
}
# Each workspace has its own state file
# dev -> terraform.tfstate.d/dev/terraform.tfstate
# staging -> terraform.tfstate.d/staging/terraform.tfstate
# prod -> terraform.tfstate.d/prod/terraform.tfstateCommon Mistake
Using workspaces as a substitute for separate root modules when environments need significantly different configurations. Workspaces work best when environments share the same structure and differ only in size, count, or naming.
Quick Fix
Use workspaces for environments that share identical infrastructure structure but vary in scale. If your prod environment needs entirely different resources or architecture than dev, use separate root modules with shared child modules instead.
Key Takeaways
- 1Workspaces = separate state per environment
- 2terraform workspace new/select/list to manage
- 3terraform.workspace gives the current workspace name
- 4Use ternary expressions for environment-specific values
- 5Best for identical structure, different scale
Was this tip helpful?
Help us improve the DevOpsPath daily collection