Skip to main content

Terraform Workspaces - Complete Guide to Managing Environments

Key Takeaway

How to use Terraform workspaces to manage multiple environments with the same configuration. Step-by-step guide with code examples and best practices for Ter...

Table of Contents

What Are Terraform Workspaces?

Workspaces allow you to maintain multiple state files for the same configuration. Each workspace has its own state, enabling you to deploy the same infrastructure to different environments.

Workspace Commands

terraform workspace list              # List all workspaces
terraform workspace new dev           # Create new workspace
terraform workspace select prod       # Switch to workspace
terraform workspace show              # Show current workspace
terraform workspace delete staging    # Delete workspace

Using Workspaces in Configuration

Reference the current workspace with terraform.workspace:

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro"

  tags = {
    Environment = terraform.workspace
  }
}

locals {
  instance_count = {
    dev     = 1
    staging = 2
    prod    = 3
  }
}

resource "aws_instance" "app" {
  count         = local.instance_count[terraform.workspace]
  instance_type = "t3.micro"
  ami           = var.ami_id
}

Workspaces vs Directory-Based Environments

Use Workspaces When

  • Environments are nearly identical
  • You want simple state separation
  • Small team, few environments

Use Separate Directories When

  • Environments differ significantly
  • You need different backends per environment
  • Large team with strict access controls
  • You want independent apply/plan cycles

Best Practices

  • Don’t use workspaces for fundamentally different infrastructure — use separate root modules instead
  • Use workspace-aware resource naming to prevent conflicts
  • Default workspace is “default” — don’t use it for production
  • Combine with variable files: terraform apply -var-file="${terraform.workspace}.tfvars"

Learn More

🚀

Level Up Your Terraform Skills

Hands-on courses, books, and resources from Luca Berton

Luca Berton
Written by

Luca Berton

DevOps Engineer, AWS Partner, Terraform expert, and author. Creator of Ansible Pilot, Terraform Pilot, and CopyPasteLearn.