Workspaces and Environments

Workspaces let one configuration keep multiple independent state files, one per environment.

Syntaxterraform workspace new staging terraform workspace select prod

Workspaces let a single configuration maintain several separate state files — useful for spinning up parallel copies of the same infrastructure.

Using workspaces

Each workspace has its own state. Switch with terraform workspace select and read the current one with terraform.workspace.

A caution

Workspaces work best for short-lived or identical environments. For durable, differently-configured environments (dev vs prod), many teams prefer separate directories or separate backends instead.

Example

Example · bash
# Create and switch to a new workspace
terraform workspace new staging

# List workspaces (* marks the current one)
terraform workspace list

# Select an existing workspace
terraform workspace select prod

# Show the active workspace
terraform workspace show

When to use it

  • A team uses workspaces named dev, staging, and production so the same directory manages three environments with separate state files.
  • An engineer creates a temporary workspace for a feature branch, applies experimental changes, and deletes the workspace when the branch is merged.
  • A Terraform configuration uses terraform.workspace in a conditional to automatically select a smaller instance type when not in the production workspace.

More examples

Create and switch workspaces

Creates a staging workspace, lists all workspaces (the * marks the active one), and switches to production.

Example · bash
# Create a new workspace
terraform workspace new staging
# Created and switched to workspace "staging"!

# List all workspaces
terraform workspace list
#   default
# * staging

# Switch to another workspace
terraform workspace select production

Use workspace name in config

Reads terraform.workspace to scale instance type and count up automatically when working in the production workspace.

Example · hcl
locals {
  instance_type = terraform.workspace == "production" ? "m5.large" : "t3.micro"
  min_instances = terraform.workspace == "production" ? 3 : 1
}

resource "aws_instance" "app" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = local.instance_type
  count         = local.min_instances
}

Delete a workspace

Shows the safe sequence for workspace cleanup: destroy managed resources, switch back to default, then delete the workspace.

Example · bash
# Destroy resources first
terraform workspace select feature-x
terraform destroy -auto-approve

# Switch away then delete
terraform workspace select default
terraform workspace delete feature-x
# Deleted workspace "feature-x"!

Discussion

  • Be the first to comment on this lesson.