Infrastructure as Code

Managing Multi-Environment State with Terraform Workspaces

NT

Naveen Teja

2/27/2026

Managing Multi-Environment State with Terraform Workspaces

Maintaining separate infrastructure environments like Development, Staging, and Production requires strict isolation of Terraform state. Copying and pasting infrastructure code across different directories violates the DRY (Don't Repeat Yourself) principle and introduces configuration drift.

Terraform Workspaces provide a native mechanism to manage multiple state files within a single working directory. By switching workspaces, Terraform automatically loads the corresponding state file from your backend (such as S3). This allows you to deploy the exact same configuration code to multiple environments with minor variable overrides.

In practice, you use the `terraform.workspace` interpolation variable within your HCL code to dynamically alter resource names, instance sizes, or tags based on the active workspace. This snippet demonstrates how to conditionally set EC2 instance types and tag resources based on the current environment.

workspaces.tf
resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  
  # Dynamically size instances based on the workspace
  instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro"

  tags = {
    Name        = "web-server-${terraform.workspace}"
    Environment = terraform.workspace
  }
}