StackPractices
intermediate By Mathias Paulenko

Isolate Environments with Terraform Workspaces

How to use Terraform workspaces for environment isolation, covering workspace creation, conditional resources, per-workspace tfvars, and migrating to separate state files.

Topics: devops

Overview

Terraform workspaces let several environments share one codebase. Each workspace gets its own state file — terraform workspace select dev switches to a state called env:/dev/... inside your backend — while .tf files stay identical for everyone. The terraform.workspace value is available in your resources, so dev can run a t3.micro and production a t3.medium from the same code.

That convenience has a hard edge: all workspaces share the same backend and provider configuration. The moment your environments need different AWS accounts, different provider settings, or materially different infrastructure, workspaces stop helping and start hiding problems.

When to Use

  • Dev, staging, and production running the same infrastructure with minor variations
  • Temporary environments for testing, demos, or per-PR validation
  • One codebase you want to keep identical across environments

When NOT to Use

  • Environments on different AWS accounts or providers — workspaces can’t switch provider configuration
  • Production with strict isolation requirements — use separate state files and backend configs
  • Environments that have diverged — if half your code is terraform.workspace conditionals, split it

Solution

Basic workspace setup

# List workspaces (default always exists)
terraform workspace list

# Create workspaces
terraform workspace new dev
terraform workspace new staging
terraform workspace new production

# Switch workspace
terraform workspace select dev

# Show the current workspace — run this before every apply
terraform workspace show

Backend configuration

Don’t interpolate terraform.workspace into the backend key — backends are evaluated before workspaces exist, so this fails at terraform init. With the S3 backend, each workspace’s state lands automatically under env:/<workspace>/ inside the bucket. One key serves every workspace:

# backend.tf
terraform {
  backend "s3" {
    bucket       = "my-company-terraform-state"
    key          = "infrastructure/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

With this config, dev state lives at env:/dev/infrastructure/terraform.tfstate, production at env:/production/infrastructure/terraform.tfstate. If you prefer a custom prefix instead of env:, set workspace_key_prefix = "workspaces". For the full bucket, locking, and IAM setup, see Store Terraform Remote State in S3 with Locking.

Environment-specific configuration

# variables.tf — terraform.workspace is a first-class value
locals {
  env_config = {
    dev = {
      instance_type     = "t3.micro"
      min_capacity      = 1
      max_capacity      = 2
      db_instance       = "db.t3.micro"
      enable_monitoring = false
    }
    staging = {
      instance_type     = "t3.small"
      min_capacity      = 2
      max_capacity      = 4
      db_instance       = "db.t3.small"
      enable_monitoring = true
    }
    production = {
      instance_type     = "t3.medium"
      min_capacity      = 3
      max_capacity      = 10
      db_instance       = "db.t3.medium"
      enable_monitoring = true
    }
  }

  config = local.env_config[terraform.workspace]
}

Conditional resources

# main.tf

# Always created
resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true

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

# Only where monitoring is enabled
resource "aws_cloudwatch_log_group" "app" {
  count             = local.config.enable_monitoring ? 1 : 0
  name              = "/app/${terraform.workspace}"
  retention_in_days = terraform.workspace == "production" ? 90 : 30
}

# Only in production
resource "aws_db_instance" "read_replica" {
  count               = terraform.workspace == "production" ? 1 : 0
  identifier          = "db-replica-${terraform.workspace}"
  replicate_source_db = aws_db_instance.primary.id
  instance_class      = local.config.db_instance
  skip_final_snapshot = true
}

Resource naming with workspace

resource "aws_s3_bucket" "app_data" {
  bucket = "my-app-${terraform.workspace}-data"

  tags = {
    Environment = terraform.workspace
  }
}

resource "aws_db_instance" "primary" {
  identifier        = "db-${terraform.workspace}"
  engine            = "postgres"
  instance_class    = local.config.db_instance
  allocated_storage = 20

  tags = {
    Environment = terraform.workspace
  }
}

Auto Scaling with workspace-specific values

resource "aws_autoscaling_group" "app" {
  name                = "asg-${terraform.workspace}"
  vpc_zone_identifier = aws_subnet.private[*].id
  min_size            = local.config.min_capacity
  max_size            = local.config.max_capacity
  desired_capacity    = local.config.min_capacity

  launch_template {
    id      = aws_launch_template.app.id
    version = "$Latest"
  }

  tag {
    key                 = "Environment"
    value               = terraform.workspace
    propagate_at_launch = true
  }
}

tfvars per workspace

# dev.tfvars
instance_count = 1
enable_ssl     = false
log_level      = "debug"
# production.tfvars
instance_count = 5
enable_ssl     = true
log_level      = "warn"
terraform workspace select dev
terraform apply -var-file="dev.tfvars"

terraform workspace select production
terraform apply -var-file="production.tfvars"

Workspace with modules

module "app" {
  source = "./modules/app"

  environment   = terraform.workspace
  instance_type = local.config.instance_type
  min_capacity  = local.config.min_capacity
  max_capacity  = local.config.max_capacity

  # Production-only features
  enable_cross_zone_load_balancing = terraform.workspace == "production"
  enable_deletion_protection       = terraform.workspace == "production"
}

CI/CD with workspaces

# .github/workflows/terraform.yml
name: Terraform

on:
  push:
    branches: [main, develop]

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1
      - uses: hashicorp/setup-terraform@v3

      - name: Select workspace
        run: |
          if [ "${{ github.ref }}" = "refs/heads/main" ]; then
            terraform workspace select production
          else
            terraform workspace select dev
          fi

      - name: Terraform Plan
        run: terraform plan -var-file="${{ github.ref == 'refs/heads/main' && 'production' || 'dev' }}.tfvars"

      - name: Terraform Apply
        if: github.event_name == 'push'
        run: terraform apply -auto-approve -var-file="${{ github.ref == 'refs/heads/main' && 'production' || 'dev' }}.tfvars"

Temporary workspaces for PRs

terraform workspace new pr-123
terraform apply -var-file="dev.tfvars"

# ... test the PR ...

terraform workspace select dev
terraform workspace delete pr-123

Workspace deletion with state cleanup

# Destroy resources first — deleting a workspace doesn't destroy them
terraform workspace select pr-123
terraform destroy -auto-approve

# You can't delete the workspace you're on
terraform workspace select default

terraform workspace delete pr-123

Explanation

flowchart diagram: terraform workspace select dev

When you run terraform workspace select dev, Terraform doesn’t change your code — it changes which state file the backend reads and writes. In S3, that mapping is a fixed env: prefix (or whatever workspace_key_prefix says), so every workspace’s objects stay in one bucket, one IAM policy, one locking setup.

The default workspace is special: its state sits at the plain key path, not under env:. That’s why existing single-environment setups keep working untouched until you create your first extra workspace.

Because provider and backend blocks evaluate before workspace selection, they can’t depend on terraform.workspace. terraform.workspace is only valid inside resources, data sources, locals, outputs, and module arguments — never inside terraform { backend ... } or provider blocks.

For the policy layer on top of this — naming, locking, IAM boundaries — see Terraform State Management Policy.

Variants

Using workspaces with locals for tags

locals {
  common_tags = {
    Environment = terraform.workspace
    ManagedBy   = "terraform"
    Project     = "my-app"
  }

  env_specific_tags = {
    dev        = { Owner = "dev-team" }
    staging    = { Owner = "qa-team" }
    production = { Owner = "ops-team" }
  }

  tags = merge(
    local.common_tags,
    local.env_specific_tags[terraform.workspace]
  )
}

resource "aws_instance" "app" {
  count         = local.config.instance_count
  instance_type = local.config.instance_type

  tags = merge(local.tags, {
    Name = "app-${terraform.workspace}-${count.index + 1}"
  })
}

Migrating from workspaces to separate state files

# 1. Export the workspace's state
terraform workspace select production
terraform state pull > production.tfstate

# 2. Point the config at a dedicated backend for production
# backend.tf
terraform {
  backend "s3" {
    bucket = "my-company-terraform-state"
    key    = "production/terraform.tfstate"
  }
}

# 3. Re-initialize and push the state
terraform init -reconfigure
terraform state push production.tfstate

# 4. Verify
terraform state list

The companion runnable workspace setup has the full backend config, env_config locals, and per-environment tfvars ready to copy.

Best Practices

  • Tag every resource with terraform.workspace — it’s the only reliable way to tell environments apart in the AWS console
  • Keep terraform.workspace conditionals rare; more than a handful means the environments have diverged
  • Run terraform workspace show in scripts before any apply — one missed select applies dev values to prod
  • Destroy before you delete: terraform workspace delete removes the state file but leaves the resources running and billing
  • Plan your exit early — if you know an environment will outgrow workspaces, start it on a separate state file instead of migrating later

Common Mistakes

  • Interpolating terraform.workspace in the backend block: key = "env/${terraform.workspace}/tfstate" fails at terraform init — backends can’t see it. The env: prefix already isolates each workspace’s state.
  • Workspaces across AWS accounts: they all share one provider config. Use separate directories or separate backend configs per account instead.
  • Applying to the wrong workspace: terraform apply on the wrong selection can destroy production. Make terraform workspace show a habit, not a checklist item.
  • Conditional sprawl: if the code is half ternaries on terraform.workspace, split into separate state files or restructure with modules.
  • Deleting without destroying: the workspace goes away, the resources stay — and keep costing money.

Frequently Asked Questions

What is a Terraform workspace?

A named state container. Each workspace has its own state file in the same backend (under env:/<name>/ in S3) but shares the same configuration, provider setup, and modules.

When should I use workspaces vs separate state files?

Workspaces for similar environments that share backend and providers — dev/staging/prod with different sizes. Separate state files when environments need different accounts, providers, or have structurally different infrastructure.

Can each workspace use a different provider or AWS account?

No. Provider and backend configuration is shared across workspaces and can't reference terraform.workspace. Per-account isolation needs separate directories or backend configs.

How do I delete a workspace?

Destroy its resources first (terraform destroy), switch to another workspace, then terraform workspace delete <name>. You can't delete default or the currently selected workspace, and deleting doesn't destroy anything — it only removes the state.

Are CLI workspaces the same as Terraform Cloud workspaces?

No. Terraform Cloud workspaces are separate entities with their own VCS connections, variables, and run settings. CLI workspaces are just separate state files sharing one config — see the official workspaces documentation.