DevOps Peach

Advanced Terraform · Environments, Import and Drift · Lesson 1 of 4

Workspaces or One Folder per Environment

CLI workspaces keep several states for one configuration; separate folders give each environment its own code, backend and permissions. Most teams use folders for environments.

Practice interactively →

You need the same infrastructure three times: dev, staging, prod. Terraform offers two ways to keep three separate states.

flowchart LR
  subgraph W["Option 1: CLI workspaces"]
    C["one folder of code"] --> WD["state env:/dev"]
    C --> WP["state env:/prod"]
  end
  subgraph F["Option 2: folder per environment"]
    D["envs/dev"] --> SD["dev/app.tfstate"]
    P["envs/prod"] --> SP["prod/app.tfstate"]
    M["modules/app"] --> D
    M --> P
  end
  %% step C: With workspaces, one configuration and one backend block hold several named states.
  %% step WD: The S3 backend stores non-default workspaces under the env:/ prefix.
  %% step D: With folders, each environment has its own small root module and backend key.
  %% step M: Both folders call the same shared module, so the real logic is written once.
  %% step SP: Prod can live in a different bucket or account, with different credentials.

CLI workspaces

terraform workspace new staging
terraform workspace select prod
terraform workspace list
terraform workspace show

Inside the code, terraform.workspace is the current name:

locals {
  replicas = terraform.workspace == "prod" ? 3 : 1
}

Comparing them

CLI workspaces Folder per environment
Code Identical for all Can differ (e.g. prod has an extra module)
Backend / account Same backend, same credentials Different bucket, account, role per env
Seeing the current env Easy to forget which one is selected The path tells you (envs/prod)
Promotion Not possible: all use the same code Bump the module version in envs/prod after dev
Good for Short-lived copies: feature branches, tests, a temporary demo Long-lived environments with different owners

HashiCorp's own guidance: CLI workspaces are not a good fit when environments need separate credentials or access controls. In HCP Terraform, a "workspace" is something different: a full unit with its own state, variables, runs and permissions, close to the folder approach.

A safe workspace habit

If you use workspaces, show the name in your prompt, and guard dangerous runs:

resource "terraform_data" "guard" {
  lifecycle {
    precondition {
      condition     = terraform.workspace != "default"
      error_message = "Select a workspace first: dev, staging or prod."
    }
  }
}

Traps: terraform workspace delete refuses to delete a workspace whose state still tracks resources, unless you add -force (which leaves those resources running and unmanaged); and running apply in the wrong selected workspace is the classic way to change prod by accident.

Practice interactively →