0
0
Terraformcloud~5 mins

Creating and switching workspaces in Terraform - Step-by-Step CLI Walkthrough

Choose your learning style9 modes available
Introduction
When you work on different versions or environments of your infrastructure, you need a way to keep their settings separate. Terraform workspaces let you create and switch between these separate environments easily.
When you want to manage development and production infrastructure separately using the same Terraform code.
When you need to test changes in a safe environment without affecting the main setup.
When multiple team members work on different features and need isolated infrastructure states.
When you want to keep infrastructure states for different clients or projects separate but use the same configuration.
When you want to quickly switch between different infrastructure setups without changing code.
Commands
This command creates a new workspace named 'dev' to isolate infrastructure state for development.
Terminal
terraform workspace new dev
Expected OutputExpected
Created and switched to workspace "dev". You are now using workspace "dev".
Lists all existing workspaces and shows which one is currently active.
Terminal
terraform workspace list
Expected OutputExpected
* default dev
Switches the current workspace to 'dev' so that Terraform commands affect this workspace's state.
Terminal
terraform workspace select dev
Expected OutputExpected
Switched to workspace "dev".
Shows the name of the currently active workspace to confirm where you are working.
Terminal
terraform workspace show
Expected OutputExpected
dev
Key Concept

If you remember nothing else from this pattern, remember: workspaces let you keep different infrastructure states separate using the same Terraform code.

Common Mistakes
Trying to create a workspace with a name that already exists.
Terraform will not create a duplicate workspace and will show an error.
Use 'terraform workspace list' to check existing workspaces before creating a new one.
Running Terraform commands without selecting the correct workspace first.
Terraform will apply changes to the wrong environment, causing confusion or errors.
Always run 'terraform workspace select <name>' to switch to the right workspace before applying changes.
Assuming workspaces isolate everything including variables and backend configuration.
Workspaces only isolate state files; variables and backend settings are shared unless configured separately.
Manage variables and backend settings carefully to avoid conflicts between workspaces.
Summary
Create a new workspace with 'terraform workspace new <name>' to isolate infrastructure state.
List all workspaces and see the current one with 'terraform workspace list'.
Switch between workspaces using 'terraform workspace select <name>' to work on different environments.
Check the active workspace anytime with 'terraform workspace show'.