Workspaces
A workspace is a separate state file for the same configuration. One set of files can manage several environments.
Create a workspace
The new workspace starts empty, with its own state.
terraform workspace new devSwitch workspaces
The same files now point at a different state.
terraform workspace select stagingSee where you are
The star marks the current workspace.
terraform workspace listExample
# main.tf
terraform {
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.0"
}
}
}
resource "local_file" "hello" {
content = "Hello from the ${terraform.workspace} workspace."
filename = "${path.module}/hello-${terraform.workspace}.txt"
}
# commands
terraform init
terraform workspace new dev
terraform apply -auto-approve
terraform workspace new staging
terraform apply -auto-approve
terraform workspace list
terraform workspace showKey points
- terraform workspace new creates a workspace. Terraform switches to it at once.
- terraform workspace select moves between workspaces. The configuration stays the same.
- terraform workspace list shows every workspace. The current one carries a star.
- terraform workspace show prints the current workspace. Check it before an apply.
- The default workspace always exists. It is where every project starts.
Each workspace wrote its own file, because terraform.workspace changes the file name. The same configuration produced two separate states. The list shows the star beside staging, the workspace in use.
Note
workspaces share variables and credentials. Only the state is separate.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What is separate in each workspace?