Terraform Workspaces

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.

Why Use Terraform Workspaces?

  • To manage multiple environments (e.g., dev, staging, prod) without duplicating configuration files.
  • To keep state files isolated for different deployments.
  • To simplify workflows when working on similar infrastructure in different contexts.

Common Terraform Workspace Commands

  • Show the current workspace: Run terraform workspace show to display the active workspace.
  • List all workspaces: Use terraform workspace list to view all available workspaces.
  • Create a new workspace: Run terraform workspace new <workspace_name> to create a workspace.
  • Switch to a different workspace: Use terraform workspace select <workspace_name> to change the active workspace.
  • Delete a workspace: Run terraform workspace delete <workspace_name> to remove a workspace (not the default one).

Example: Managing Multiple Workspaces

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.

Use Case

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.

Conclusion

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.