interview-prep

Crisp answer: Workspaces give you separate state files within the same backend, allowing multiple instances of the same config. They are useful for managing multiple environments but have limitations — most teams prefer separate directories or separate backends per environment.

How workspaces work:

# List workspaces
terraform workspace list
# * default
#   staging
#   production

# Create and switch
terraform workspace new staging
terraform workspace select production

# Current workspace
terraform workspace show

Each workspace gets its own state file in the backend:

s3://my-state-bucket/
├── terraform.tfstate           # default workspace
├── env:/
│   ├── staging/terraform.tfstate
│   └── production/terraform.tfstate

Using workspace name in config:

locals {
  instance_type = terraform.workspace == "production" ? "t3.large" : "t3.small"
  replica_count = terraform.workspace == "production" ? 3 : 1
}

resource "aws_instance" "web" {
  instance_type = local.instance_type
  count         = local.replica_count
}

When workspaces are appropriate:

  • Short-lived feature environments spun up and destroyed frequently
  • Testing infrastructure changes before promoting to production
  • Situations where all environments use exactly the same config structure

When workspaces are NOT appropriate:

  • Long-lived environments with meaningfully different configs
  • Environments that require different backends (different AWS accounts)
  • Teams where environment isolation is a compliance requirement

The preferred alternative — directories per environment:

infra/
├── modules/
│   ├── vpc/
│   └── eks/
├── environments/
│   ├── dev/
│   │   ├── main.tf      # calls modules, dev-specific vars
│   │   ├── backend.tf   # dev state bucket
│   │   └── terraform.tfvars
│   ├── staging/
│   │   ├── main.tf
│   │   ├── backend.tf   # staging state bucket
│   │   └── terraform.tfvars
│   └── prod/
│       ├── main.tf
│       ├── backend.tf   # prod state bucket, different AWS account
│       └── terraform.tfvars

Each environment is a separate Terraform root with its own state, its own backend, and its own variable values. No risk of accidentally applying production changes to staging.

What to say in the interview:

"Workspaces give you separate state files for the same config. They're useful for ephemeral environments but I prefer separate directories per environment for long-lived infrastructure. The reason: separate directories mean separate backends, separate state, and no risk of selecting the wrong workspace before an apply. Workspaces also make it easy to accidentally workspace select production when you intended staging. Directories make that impossible."


My notes