Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Workflows and Collaboration

Terraform Workspaces and Managing Multiple Environments

Compare Terraform workspaces, directory-per-environment and tfvars layouts for dev, staging and prod. Learn when each pattern is safe and how to avoid cross-environment mistakes.

Almost every project needs more than one copy of its infrastructure: dev to experiment, staging to rehearse, production to serve users. The question is how to organize Terraform so that the three copies stay similar but cannot damage each other. Terraform offers workspaces, but most teams also use separate directories or separate state keys. This lesson compares the options honestly.

What a workspace is

A workspace is a named state inside one backend and one configuration. The default one is called default.

Terminal
terraform workspace list
terraform workspace new staging
terraform workspace select staging
terraform workspace show
terraform workspace delete staging

With the S3 backend the states live at env:/staging/PATH/terraform.tfstate. Your code can read the current name with terraform.workspace:

HCL
locals {
  env = terraform.workspace

  sizes = {
    default = "t3.micro"
    staging = "t3.small"
    prod    = "m6i.large"
  }
}

resource "aws_instance" "web" {
  instance_type = local.sizes[local.env]
  tags          = { Name = "web-${local.env}" }
}

Workspaces are fast to create and share exactly the same code. That is both their strength and their weakness: nothing in the filesystem tells you which environment you are about to change.

Python One configuration, several states

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When workspaces fit, and when they do not

Good uses:

  • Short-lived copies: a preview environment per pull request, torn down after the merge.
  • Identical stacks per customer or region where the only change is a name.

Weak uses:

  • Long-lived prod and non-prod. Same code means you cannot change staging first and promote the change later; the next apply in prod uses today's code. Permissions are also awkward: you usually want developers to apply to dev but not to prod, and workspaces share one backend and one credential.
  • Environments that differ structurally (prod has a replica database, dev does not).

HashiCorp's own documentation says workspaces are not a good way to separate environments that need different credentials or access controls.

Directory per environment

The most common long-lived layout keeps environments in separate folders, each with its own backend key, and shares code via modules:

TEXT
infra/
  modules/
    app/
  envs/
    dev/
      main.tf          # module "app" { source = "../../modules/app" ... }
      backend.tf       # key = "dev/app/terraform.tfstate"
      terraform.tfvars
    staging/
    prod/
HCL
# envs/prod/main.tf
module "app" {
  source         = "../../modules/app"
  environment    = "prod"
  instance_type  = "m6i.large"
  instance_count = 4
  enable_replica = true
}

Benefits: every environment is explicit, reviewers see which folder a pull request touches, and CI can map folders to credentials and approval rules (prod needs two reviewers). The cost is duplication of a few lines per environment; keep the folders thin by putting all logic in modules (Designing Good Modules).

One folder, many tfvars files

A middle path keeps one root module and selects settings with a var file and a backend key:

Terminal
terraform init -backend-config=backends/prod.hcl -reconfigure
terraform plan -var-file=envs/prod.tfvars

It is easy to wire into CI, but a developer can forget -reconfigure and run a prod var file against the dev backend. Wrapper scripts or tools such as Terragrunt reduce this risk.

flowchart TD
  Q{"How different and how long-lived are the environments?"}
  Q -->|"Identical and short-lived"| W["Workspaces"]
  Q -->|"Long-lived, different access rules"| D["Directory per environment + shared modules"]
  Q -->|"Same shape, tooling enforces the backend"| T["One folder + tfvars + wrapper"]

Pick the layout that makes the wrong action hard to do.

Python Guard against applying to the wrong environment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Separate accounts per environment

Whatever layout you choose, put production in its own cloud account (AWS account, Azure subscription, GCP project). A provider block can assume a role per environment, so even a mistaken apply from a dev machine fails with "access denied" instead of changing prod:

HCL
provider "aws" {
  region = "eu-central-1"

  assume_role {
    role_arn = var.deploy_role_arn   # different per environment
  }
}

Promoting changes

With directories, the promotion flow is natural: merge a change, apply dev, then staging, then prod, each step gated by CI approvals. Use identical module versions in all environments, and bump the version in dev first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you read the current workspace name in HCL?

    terraform.workspace is a built-in value holding the selected workspace name.
  2. 2. Which use of workspaces is generally appropriate?

    Workspaces suit identical, disposable copies, not environments with different access rules.
  3. 3. What is the main advantage of a directory per environment?

    The folder makes the target environment visible and lets CI apply different rules per folder.
  4. 4. How does a separate cloud account reduce risk?

    Account boundaries are a hard permission wall that no flag mistake can cross.

Summary

  • Workspaces give each name its own state in one backend; use terraform.workspace in code.
  • They fit identical, short-lived copies, not long-lived prod versus non-prod.
  • Directory-per-environment with shared modules is the most common long-lived layout.
  • Make the wrong action hard: separate backends, accounts and credentials per environment.
  • Promote changes dev, then staging, then prod, with the same module versions.

Next: Terraform in CI/CD