You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Managing multiple environments (development, staging, production) is a core challenge in infrastructure as code. Terraform provides several approaches: workspaces, directory structures, and variable files. This lesson covers each approach and when to use them.
Workspaces allow you to maintain multiple instances of state for the same configuration:
terraform workspace new staging
terraform workspace new production
terraform workspace list
terraform workspace select staging
Each workspace has its own state file:
terraform.tfstate.d/
├── staging/
│ └── terraform.tfstate
└── production/
└── terraform.tfstate
Access the current workspace name with terraform.workspace:
resource "aws_instance" "web" {
ami = var.ami_id
instance_type = terraform.workspace == "production" ? "t3.large" : "t3.micro"
tags = {
Environment = terraform.workspace
}
}
| Command | Purpose |
|---|---|
terraform workspace list | List all workspaces |
terraform workspace new <name> | Create a new workspace |
terraform workspace select <name> | Switch to a workspace |
terraform workspace delete <name> | Delete a workspace |
terraform workspace show | Show the current workspace |
| Good Fit | Poor Fit |
|---|---|
| Same infrastructure, different instances | Very different configurations per environment |
| Testing changes before promoting | Different providers or backends per environment |
| Short-lived environments | Teams that need strict isolation |
Tip: Workspaces are best for lightweight environment separation. For production-grade isolation, consider directory-based environments or Terraform Cloud workspaces.
A more explicit approach is to use separate directories for each environment:
infrastructure/
├── modules/
│ ├── network/
│ ├── compute/
│ └── database/
├── environments/
│ ├── development/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── terraform.tfvars
│ │ └── backend.tf
│ ├── staging/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── terraform.tfvars
│ │ └── backend.tf
│ └── production/
│ ├── main.tf
│ ├── variables.tf
│ ├── terraform.tfvars
│ └── backend.tf
| Advantage | Description |
|---|---|
| Full isolation | Each environment has its own state and backend |
| Different configurations | Environments can diverge when needed |
| Clear blast radius | A mistake in staging cannot affect production |
| Separate permissions | Different IAM roles per environment backend |
environments/development/terraform.tfvars:
environment = "development"
instance_type = "t3.micro"
instance_count = 1
enable_ha = false
environments/production/terraform.tfvars:
environment = "production"
instance_type = "t3.large"
instance_count = 3
enable_ha = true
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.