Skip to main content

Terraform Workspace

Imagine you’re running your Lego city with Terraform. You’ve got one master blueprint, but you want to build different versions of the city: a small prototype (dev), a medium‑sized test city (staging), and a full‑scale metropolis (production).

Instead of copying the blueprint three times, Terraform lets you use workspace that separate “drawers” that hold different state files while sharing the same configuration. Workspaces make it easy to manage multiple environments without duplicating code.


Key Concepts

1. What is a Workspace?

  • A workspace is an isolated state environment within a single Terraform configuration.
  • Each workspace has its own state file, but all share the same .tf code.
  • Default workspace: default.

2. Why Use Workspaces?

  • Environment separation: Manage dev, staging, and prod with the same config.
  • State isolation: Each workspace keeps its own state file, preventing conflicts.
  • Consistency: Same infrastructure design applied across environments.
  • Efficiency: Avoid duplicating .tf files for each environment.

3. Example Scenario

  • You have a VPC module defined in main.tf.
  • In dev workspace, you deploy a small VPC with 1 subnet.
  • In prod workspace, you deploy a larger VPC with 4 subnets.
  • Both use the same code, but states are isolated by workspace.

4. Workspace Lifecycle

  • Create: terraform workspace new dev
  • Switch: terraform workspace select prod
  • List: terraform workspace list
  • Show current: terraform workspace show

Hands‑On Lab / Demo

Lab: Using Workspaces for Environments

  1. Run terraform apply → Dev workspace deploys small instances, Prod workspace deploys larger ones.

Deploy resources with environment‑specific variables:

variable "instance_type" {
  default = terraform.workspace == "prod" ? "t3.large" : "t2.micro"
}

Switch to it:

terraform workspace select dev

Create a new workspace:

terraform workspace new dev

Pro Tips & Best Practices

  • Use workspaces for environment separation, not for every minor variation.
  • Keep naming consistent (dev, staging, prod).
  • Avoid mixing critical production state with experimental workspaces.
  • Document workspace usage in project README.
  • For large teams, consider separate state backends instead of workspaces.

Summary & Cheatsheet

  • Workspaces = Isolated state environments.
  • Default workspace: default.
  • Commands: new, select, list, show.
  • Use case: Manage dev, staging, prod with same config but separate states.
Quick mnemonic: One Code, Many States

The Hackers Notebook

Workspaces are Terraform’s way of giving you multiple environments from one configuration. They let you separate state files while reusing the same code, making environment management simple and efficient.


Tips, Tricks, Roadmaps, Resources, Networking, Motivation, Guidance, and Cool Stuff ♥

Updated on Dec 31, 2025