Terraform Workspaces — a way to manage multiple environments (dev, staging, prod) from a single codebase.
Simple analogy: Workspaces are like pages in an Excel file. You have one file (code), but different pages (workspace) for dev, staging, and prod.
How it works:
1# Create workspace2terraform workspace new dev3terraform workspace new staging4terraform workspace new prod56# Switch7terraform workspace select dev89# View current10terraform workspace show1112# List all13terraform workspace list1415# Delete16terraform workspace delete staging
Usage in code:
1resource "aws_instance" "web" {2 instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro"3 tags = {4 Environment = terraform.workspace5 }6}
Alternative — directory-based:
infrastructure/
dev/
main.tf
staging/
main.tf
prod/
main.tf
Workspaces vs Directory-based: