Skip to main content
Terraform intermediate Lesson 10 of 11

Workspaces and Environments (dev/stage/prod patterns)

Learn Terraform workspaces and recommended environment isolation patterns. Includes examples and safe practices.

Terraform supports multiple ways to manage environments. Two common approaches:

  • Separate state per environment (recommended in most teams)
  • Terraform workspaces (a built-in way to vary state)

Learning outcomes

You’ll be able to:

  • explain what workspaces are
  • choose an environment isolation strategy
  • avoid the most common workspace/state mistakes

1) Why environments matter

Environments isolate risk:

  • dev changes shouldn’t affect prod
  • credentials and policies differ
  • you want reproducible, auditable changes per environment

2) Terraform workspaces (concept)

A Terraform workspace selects a separate state file. State name example:

  • default workspace → terraform.tfstate
  • dev workspace → terraform.tfstate.d/dev

Basic commands:

# list workspaces
terraform workspace list

# create and switch
terraform workspace new dev

# switch
terraform workspace select dev

3) Using workspace in configuration

Workspaces expose their name via terraform.workspace. Example:

locals {
  env = terraform.workspace
}

resource "null_resource" "example" {
  triggers = {
    env = local.env
  }
}

You would then use local.env to drive naming:

  • app-${local.env}-bucket

Instead of workspaces, configure your remote backend so each environment has its own state file (key).

Conceptual example:

  • envs/dev/terraform.tfstate
  • envs/prod/terraform.tfstate

In practice, you implement this by parameterizing backend config (often through CLI or separate backend config files).

Why this is often preferred:

  • clearer separation
  • fewer surprises when switching workspaces
  • easier to reason about what state you’re pointing at

5) Practical guidance

If you use workspaces

  • keep naming based on terraform.workspace
  • never accidentally run against the wrong workspace
  • always use terraform plan after switching

If you don’t use workspaces

  • define environment variables for naming and configuration
  • ensure backend keys differ per env

6) Cleanup reminder

If using workspaces, destroy in the correct workspace:

terraform workspace select dev
terraform destroy

Frequently Asked Questions

Should I use workspaces for dev/stage/prod?
Often it’s safer to use separate state backends/keys per environment. Workspaces can work, but teams frequently prefer explicit environment separation for clarity and safety.