Explain Terraform workspace strategies for managing multiple environments. Compare per-environment workspaces versus per-component workspaces, and when would you use neither and instead use directory-based separation?
Quick Answer
Per-environment workspaces (dev/staging/prod) share code but risk configuration drift; per-component workspaces separate blast radius but increase complexity; directory-based separation provides maximum isolation but duplicates code. Most mature organizations use a hybrid: directories for environments with workspaces for regional variations.
Detailed Answer
Strategy 1: Per-Environment Workspaces (terraform workspace) Use terraform workspace new dev/staging/prod with environment-specific .tfvars files. Same code, same state backend, different workspace-isolated state files. - Pros: DRY code, easy to promote changes through environments - Cons: All environments share the same backend permissions, accidental terraform destroy in wrong workspace is catastrophic, can't have different module versions per environment - Anti-pattern: Using terraform.workspace in conditionals creates implicit differences between environments that are hard to track
Strategy 2: Per-Component Workspaces Each infrastructure component (networking, compute, data) gets its own workspace. Promotes independent lifecycle management. - Pros: Small blast radius, fast plan/apply, team ownership boundaries - Cons: Cross-workspace dependencies require data sources or remote state, ordering of applies matters
Strategy 3: Directory-Based Separation Separate directories: environments/dev/, environments/staging/, environments/prod/, each with their own backend config and state. - Pros: Maximum isolation, different module versions per environment, independent credentials - Cons: Code duplication, drift between environments, harder to promote changes
Recommended Hybrid Approach
Use Terragrunt with directory-based environments that reference shared modules with pinned versions. Each environment directory contains a terragrunt.hcl that specifies the module source version. Promotions happen by updating the version pin (e.g., dev uses v2.1.0, prod uses v2.0.3).
Terraform Cloud Approach
Use workspaces mapped to VCS branches or directories. Tag-based workspace organization. Run triggers for dependencies between workspaces. Variable sets for shared configuration across workspace groups.