Terraform Tutorial — Workspaces vs Directories

1 minute read

There are two approaches to managing multiple environments: workspaces and separate directories. Each has trade-offs.


Approach 1: Workspaces

project/
├── main.tf
├── variables.tf
├── outputs.tf
├── dev.tfvars
├── staging.tfvars
└── prod.tfvars
$ terraform workspace select dev
$ terraform apply -var-file="dev.tfvars"

$ terraform workspace select prod
$ terraform apply -var-file="prod.tfvars"

Approach 2: Separate Directories

project/
├── modules/
│   └── app/
├── environments/
│   ├── dev/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── terraform.tfvars
│   ├── staging/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── terraform.tfvars
│   └── prod/
│       ├── main.tf
│       ├── variables.tf
│       └── terraform.tfvars
$ cd environments/dev && terraform apply
$ cd environments/prod && terraform apply

Comparison

Aspect Workspaces Directories
Code duplication None Some (main.tf in each env)
Different configs per env Via terraform.workspace conditionals Via separate .tf files
State isolation Automatic By separate backend keys
Provider differences Shared Can differ per environment
Complexity Simple for similar envs Better for different envs
CI/CD Must select workspace cd to directory
Risk of wrong workspace Possible Not possible (explicit path)

When to Use Each

Use Workspaces When Use Directories When
Environments are nearly identical Environments differ significantly
Same providers everywhere Different providers per env
Small team, few environments Large team, strict access control
Quick prototyping Production-grade setup

What’s Next?

Let’s see a complete multi-environment pattern using workspaces.


← Workspace Interpolation Multi-Environment Pattern →