Skip to main content

Module 10, Workspaces

What are Workspaces

Workspaces allow multiple isolated state files within the same backend and configuration. Each workspace has its own terraform.tfstate.

terraform workspace list # show all workspaces
terraform workspace new dev # create dev workspace
terraform workspace new production # create production workspace
terraform workspace select dev # switch to dev
terraform workspace show # show current workspace

Using Workspace Name in Config

locals {
environment = terraform.workspace # "dev", "staging", "production"
}

resource "aws_instance" "app" {
instance_type = terraform.workspace == "production" ? "t3.small" : "t3.micro"

tags = {
Environment = terraform.workspace
}
}

Workspace vs Separate State Files

ApproachProsCons
WorkspacesSimple, one configEasy to accidentally apply to wrong env
Separate dirs per envClear separation, different configsMore code repetition
TerragruntDRY, full separationExtra tool to learn
tip

For production use, separate state files per environment (different key in the S3 backend) provide stronger isolation than workspaces. Workspaces are great for feature branches and temporary environments.

HCP Terraform Workspaces

HCP Terraform workspaces are not the same as CLI workspaces. In HCP Terraform, a workspace is a full environment with its own:

  • State file
  • Variable set
  • Run history
  • Team access controls

This is a common exam trick question.

Knowledge Check

  1. What does terraform workspace new staging do?
  2. How do you reference the current workspace name in configuration?
  3. What is the default workspace name?
  4. True or False: HCP Terraform workspaces are the same as Terraform CLI workspaces.
  5. When would you use workspaces vs separate state files per environment?
Exam Mapping
  • HashiCorp Associate Obj 9: Understand HCP Terraform capabilities