Skip to main content

Workspaces for Environments

Think of Terraform workspaces as different drawers in your control cabinet. Each drawer holds a separate version of your Lego city: one for dev experiments, one for staging rehearsals, and one for production reality.

The blueprint (Terraform configuration) stays the same, but each drawer has its own state file, ensuring changes in dev don’t spill into prod. Workspaces give you a clean, organized way to manage multiple environments without duplicating code.


Key Concepts

1. Environment Separation

  • Each workspace has its own state file.
  • All workspaces share the same .tf configuration.
  • Prevents accidental overlap between environments.

2. Built‑In Variable: terraform.workspace

  • Result: Dev/staging use smaller instances, prod uses larger ones.

Terraform provides a special variable:

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

3. Example Scenario

  • Dev workspace: 1 EC2 instance for testing.
  • Staging workspace: 2 EC2 instances for QA.
  • Prod workspace: 5 EC2 instances for real traffic.
  • Same main.tf file, different states per workspace.

4. Workspace Workflow

Apply configuration → Resources are deployed according to workspace‑specific logic.

Switch between them:

terraform workspace select prod

Create workspaces:

terraform workspace new dev
terraform workspace new staging
terraform workspace new prod

Hands‑On Lab / Demo

Lab: Multi‑Environment Deployment with Workspaces

  1. Run terraform apply in each workspace:
    • Dev → 1 instance.
    • Staging → 2 instances.
    • Prod → 5 instances.

Use it in resource:

resource "aws_instance" "app" {
  count         = var.replica_count
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

Define variable logic:

variable "replica_count" {
  default = terraform.workspace == "prod" ? 5 : terraform.workspace == "staging" ? 2 : 1
}

Pro Tips & Best Practices

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

Summary & Cheatsheet

  • Workspaces = Environment isolation with shared config.
  • Built‑in variable: terraform.workspace.
  • Use case: Separate dev, staging, prod without duplicating code.
  • Workflow: Create → Select → Apply.
Quick mnemonic: One Config, Many Environments

The Hackers Notebook

Workspaces are Terraform’s environment drawers, giving you isolated states for dev, staging, and prod while reusing the same configuration. They simplify environment management, reduce duplication, and keep production safe from experimental changes.


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

Updated on Dec 28, 2025