How to Switch Workspace in Terraform: Simple Steps
To switch workspace in Terraform, use the command
terraform workspace select <workspace_name>. This changes your current workspace to the specified one, allowing you to manage different infrastructure states separately.Syntax
The command to switch workspace in Terraform is:
terraform workspace select <workspace_name>: Switches to the workspace named<workspace_name>.- If the workspace does not exist, Terraform will show an error.
- You can list existing workspaces with
terraform workspace list.
bash
terraform workspace select <workspace_name>
Example
This example shows how to switch from the default workspace to a workspace named dev. It also shows how to list workspaces before switching.
bash
terraform workspace list # Output: # * default # dev terraform workspace select dev # Output: # Switched to workspace "dev".
Output
Switched to workspace "dev".
Common Pitfalls
Common mistakes when switching workspaces include:
- Trying to select a workspace that does not exist, which causes an error.
- Not initializing Terraform before switching, which can cause unexpected behavior.
- Confusing workspaces with different backend configurations; workspaces share the same backend.
bash
terraform workspace select staging # Error: No workspace named "staging" exists. # Correct approach: terraform workspace new staging terraform workspace select staging
Quick Reference
Here is a quick cheat-sheet for workspace commands:
| Command | Description |
|---|---|
| terraform workspace list | List all existing workspaces |
| terraform workspace show | Show the current workspace |
| terraform workspace new | Create a new workspace |
| terraform workspace select | Switch to an existing workspace |
| terraform workspace delete | Delete a workspace |
Key Takeaways
Use
terraform workspace select <name> to switch workspaces.List workspaces first with
terraform workspace list to see available options.Create a workspace with
terraform workspace new <name> if it does not exist.Always initialize Terraform before switching workspaces to avoid errors.
Workspaces share the same backend but keep separate state files.