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
| Approach | Pros | Cons |
|---|---|---|
| Workspaces | Simple, one config | Easy to accidentally apply to wrong env |
| Separate dirs per env | Clear separation, different configs | More code repetition |
| Terragrunt | DRY, full separation | Extra 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
- What does
terraform workspace new stagingdo? - How do you reference the current workspace name in configuration?
- What is the default workspace name?
- True or False: HCP Terraform workspaces are the same as Terraform CLI workspaces.
- When would you use workspaces vs separate state files per environment?
Exam Mapping
- HashiCorp Associate Obj 9: Understand HCP Terraform capabilities