Loading

Quipoin Menu

Learn • Practice • Grow

terraform / Terraform Workspaces
tutorial

Terraform Workspaces

Terraform workspaces allow you to manage multiple distinct states for the same configuration. They are useful for environments like dev, stage, and prod without duplicating code.

What Are Workspaces?

A workspace is a named state container. The default workspace is called default. You can create additional workspaces, and each has its own state file. This lets you use the same configuration to deploy infrastructure to different environments.

Workspaces keep multiple independent states within the same configuration.

Workspace Commands

  • List workspaces: terraform workspace list
  • Create a new workspace: terraform workspace new dev
  • Switch workspace: terraform workspace select dev
  • Show current workspace: terraform workspace show

Using Workspace Name in Configuration

Access the current workspace name with terraform.workspace. Use it to differentiate resources.
resource "aws_instance" "web" {
ami = "ami-abc123"
instance_type = terraform.workspace == "prod" ? "t3.large" : "t2.micro"
tags = {
Name = "web-${terraform.workspace}"
}
}

Workspaces and Remote State

When using remote backends (e.g., S3), workspaces map to different state files. For S3, the key pattern becomes env:/<workspace>/terraform.tfstate.

When to Use Workspaces

Workspaces are great for small differences (like names or instance sizes). For more complex differences (e.g., completely different VPCs), consider using separate configurations or modules with variables. Many teams prefer using variable files (.tfvars) over workspaces.


Two Minute Drill
  • Workspaces manage multiple states for the same configuration.
  • Commands: workspace new, select, list, show.
  • Use terraform.workspace to access the current workspace name.
  • Each workspace has its own state file (local or remote).

Need more clarification?

Drop us an email at career@quipoinfotech.com