Workspaces: Managing Multiple Environments

Learn how to use Terraform workspaces to separate dev, staging & prod, automate state, and scale multi-env infrastructure with less risk.

Workspaces are frequently misunderstood in terms of their appropriate use cases.

The Problem

# Overreliance on workspaces for environment separation
terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "terraform.tfstate"
    region = "us-west-2"
  }
}

# Attempting to use workspace for environment-specific config
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = terraform.workspace == "prod" ? "m5.large" : "t2.micro"
  
  tags = {
    Environment = terraform.workspace
  }
}

The Solution

# Use directory structure for complete environment separation
# ./environments/prod/main.tf
terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "environments/prod/terraform.tfstate"
    region = "us-west-2"
  }
}

module "application" {
  source = "../../modules/application"
  
  environment   = "prod"
  instance_type = "m5.large"
}

# ./environments/dev/main.tf
terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "environments/dev/terraform.tfstate"
    region = "us-west-2"
  }
}

module "application" {
  source = "../../modules/application"
  
  environment   = "dev"
  instance_type = "t2.micro"
}

Workspaces should be used for temporary or experimental changes, not for environment separation. Scalr takes environment management to the next level with true environment isolation, fine-grained access controls, and environment-specific variables.

For additional reading on Terraform Workspaces see:

Terraform Workspaces Explained
Compare workspaces across Terraform CLI, Terraform Cloud and Scalr. Quickly grasp differences in state, variables, policy control and choose the right tool.

For additional reading specifically on Terraform environment management, see:

Terraform Workspaces for Environment Management
Learn how Terraform workspaces isolate dev, staging & prod, secure state files, and streamline multi-environment IaC management.