Skip to content

Lesson 3 of 9 · 21m

Workspaces vs Directories for Environments

When Terraform workspaces help, when they hide too much, and why mature teams usually choose explicit directory layout.

Every growing Terraform estate reaches the same argument: one codebase with workspaces, or directories per environment. Both can work. The wrong answer is choosing workspaces because they look DRY while your environments are not actually the same shape.

Workspaces select a state instance, not a magic environment system

terraform workspace new staging
terraform workspace select prod
terraform plan

Inside configuration you can branch on terraform.workspace:

locals {
  instance_count = terraform.workspace == "prod" ? 6 : 2
}

That mechanism is useful for genuinely parallel instances of the same stack: ephemeral review environments, regional copies of a service, or tenant-isolated instances with identical topology. It becomes dangerous when production differs structurally — extra accounts, regulatory controls, different modules, different providers — because one conditional at a time the codebase turns into a maze.

The hidden footgun is invisible context

A directory tells the operator where they are. A workspace often does not. Engineers have destroyed production after running commands in the correct folder but with the wrong selected workspace. Mitigate it if you use workspaces:

terraform workspace show
terraform plan -var-file="env/prod.tfvars"

Even better, wrap operations in a task runner that refuses prod actions unless the selected workspace matches the variable file. Never rely on memory as a control system.

Directories make difference explicit

A common scaled layout is:

live/
  prod/
    network/
    billing-api/
  staging/
    network/
    billing-api/
modules/
  network/
  service/

The duplication people fear is mostly small composition code: backend configuration, provider settings, module inputs. That duplication is valuable because differences are visible in review. prod can use different providers, a different account, additional controls, or a pinned older module version while staging moves ahead.

The deciding question

Ask: are environments copies of one architecture, or stages of one release pipeline? Copies with intentionally identical structure can use workspaces. Stages with different risk, approval, dependencies, or account boundaries almost always deserve directories and separate state keys.

Field notes

  • Do not put secrets in tfvars just because workspaces feel convenient; environment isolation needs secret isolation too.
  • terraform.workspace returns default unless selected; CI must select explicitly or fail closed.
  • Directory duplication is cheap compared with untangling environment-specific conditionals later.
  • Ephemeral pull request environments are the strongest legitimate use case for workspaces.

Was this lesson helpful?

Sign in to rate