The problem
You want dev and prod infrastructure at the same time from one set of .tf files.
Without workspaces (common beginner mistake)
dev.tfvars / prod.tfvars alone are not enough if they share one state file.
terraform apply -var-file=dev.tfvars # creates dev-server
terraform apply -var-file=prod.tfvars # replaces it with prod-serverTerraform compares desired state to the same state file, so it modifies or replaces the existing resource instead of creating a second environment.
terraform.tfstate
↓
dev-server
↓
apply prod.tfvars
↓
replace with prod-server
Manual alternative
Separate state files:
terraform apply -var-file=dev.tfvars -state=dev.tfstate
terraform apply -var-file=prod.tfvars -state=prod.tfstateThat works, but juggling many -state flags gets messy.
With workspaces
Workspaces give each environment its own state automatically.
terraform workspace new dev
terraform workspace new prod
terraform workspace listExample list:
* default
dev
prod
terraform workspace select dev
terraform apply # creates the dev environment
terraform workspace select prod
terraform apply # creates the prod environmentDynamic naming with terraform.workspace
resource "aws_instance" "ec2_instance" {
ami = "ami-0199ac7c9fbf9ed83"
instance_type = "t3.micro"
tags = {
Name = "${terraform.workspace}-server"
}
}| Workspace | Tag |
|---|---|
dev | dev-server |
prod | prod-server |
Local workspace layout
Workspace: dev
→ terraform.tfstate.d/dev/
→ dev-server
Workspace: prod
→ terraform.tfstate.d/prod/
→ prod-server
Each workspace → separate state → separate infrastructure.
Workspaces + remote S3 backend
With:
backend "s3" {
bucket = "terraform-state-file-test-1234"
key = "global/s3/terraform.tfstate"
region = "ap-south-2"
use_lockfile = true
}Terraform stores workspace state under keys like:
global/s3/terraform.tfstate → default
env:/dev/global/s3/terraform.tfstate → dev
env:/prod/global/s3/terraform.tfstate → prod
You do not need a separate backend block per environment.
Commands to know
terraform workspace new dev
terraform workspace list
terraform workspace select prod
terraform workspace show
terraform workspace delete devInterview-style summary
Without workspaces
→ one code, one state, one environment
→ switching tfvars can replace resources
With workspaces
→ one code, multiple states, multiple environments
→ dev / qa / prod can coexist
Workspaces are a good fit for similar environments that share the same shape. For very different stacks (or stronger isolation), many teams prefer separate directories or separate state backends per environment.