Terraform Tutorial · State and Workflow · Lesson 20 of 25

Terraform Environments and Workspaces

Run the same configuration for dev, staging and production: separate directories, tfvars files, and when (not) to use workspaces.

modules/
  app/
envs/
  dev/      main.tf   backend.tf   terraform.tfvars
  staging/  main.tf   backend.tf   terraform.tfvars
  prod/     main.tf   backend.tf   terraform.tfvars

Each environment has its own state and backend key, calls the same modules, and can be locked down separately. Mistakes stay contained.

Option 2: workspaces

terraform workspace new staging creates a separate state for the same directory, and terraform.workspace tells your code which one is active.

Per-workspace settings
locals {
  settings = {
    default = { size = "small", replicas = 1 }
    prod    = { size = "large", replicas = 3 }
  }
  current = lookup(local.settings, terraform.workspace, local.settings["default"])
}

output "workspace" {
  value = "${terraform.workspace}: ${local.current.replicas} x ${local.current.size}"
}

Output

workspace = "default: 1 x small"

Run this on your computer — see “Get Started” for setup.

Workspaces share one backend and one set of credentials, so they are convenient for short-lived copies (a feature branch environment) but risky for keeping production apart.

Promotion

Apply changes to dev first, then staging, then prod, with the same module version, usually through a CI/CD pipeline with a manual approval before production.

Test yourself

Why do many teams prefer one directory per environment over workspaces for production?

  1. Workspaces are deprecated
  2. Separate state, backend and permissions keep mistakes contained
  3. Directories are faster
  4. Workspaces can't use variables
Show answer

Answer: Separate state, backend and permissions keep mistakes contained