Multi-Environment Workspace Management
Intermediate10 min
Use Terraform workspaces to manage multiple environments like dev, staging, and production from a single configuration.
Prerequisites
- -Terraform installed
- -Remote backend configured
Steps
1
List existing workspaces
View all available workspaces. The asterisk marks the currently selected workspace.
$ terraform workspace list
2
Create workspaces for each environment
Create separate workspaces for dev, staging, and production environments.
$ terraform workspace new dev && terraform workspace new staging && terraform workspace new prod
Each workspace maintains its own independent state file, so resources are fully isolated.
3
Switch between workspaces
Select the workspace you want to operate in before running plan or apply.
$ terraform workspace select staging
4
Use workspace name in configuration
Reference terraform.workspace to parameterize resources per environment.
$ cat <<'EOF' > main.tf
locals {
env = terraform.workspace
}
resource "aws_instance" "app" {
instance_type = local.env == "prod" ? "t3.large" : "t3.micro"
tags = {
Environment = local.env
}
}
EOF
5
Use workspace-specific variable files
Load environment-specific variables automatically based on the active workspace.
$ terraform plan -var-file="envs/${terraform.workspace}.tfvars"
Create envs/dev.tfvars, envs/staging.tfvars, and envs/prod.tfvars with environment-specific values.
Full Script
FAQ
Discussion
Loading comments...