When managing infrastructure, it’s common to have separate environments for development, staging, and production. Terraform workspaces provide a way to manage multiple states within a single configuration directory, allowing you to deploy the same infrastructure across different environments seamlessly.
terraform workspace show
to display the active workspace.terraform workspace list
to view all available workspaces.terraform workspace new <workspace_name>
to create a workspace.terraform workspace select <workspace_name>
to change the active workspace.terraform workspace delete <workspace_name>
to remove a workspace (not the default one).Suppose you’re working on a project with three environments: dev, staging, and prod. To create and switch between these environments:
Create a new workspace for development:terraform workspace new dev
Output:
Created and switched to workspace "dev"!
Verify the active workspace:terraform workspace show
Output:
dev
Add workspaces for staging and production:terraform workspace new stagingterraform workspace new prod
List all workspaces:terraform workspace list
Output:
default
* dev
staging
prod
Switch to the staging workspace:terraform workspace select staging
Output:
Switched to workspace "staging".
Each workspace maintains its own state file, allowing you to deploy the same configuration to different environments.
Imagine you’re deploying a new feature to a staging environment for testing before pushing it to production. By switching workspaces, you can apply changes to the staging environment without affecting production, ensuring a safer deployment process.
Terraform workspaces are a powerful tool for managing multiple environments in a single configuration. By isolating state files, they simplify workflows and reduce the risk of cross-environment conflicts. Mastering workspace commands can significantly enhance your Terraform efficiency.