Infrastructure as Code FAQ: Top Questions
5. What are Terraform Workspaces and how do they help manage environments?
Terraform Workspaces provide a mechanism to manage multiple distinct versions of the same infrastructure within a single configuration โ typically used to manage different environments like dev, staging, and production.
๐บ๏ธ Step-by-Step Instructions:
- Initialize your Terraform project using
terraform init
. - Create a new workspace using
terraform workspace new <name>
. - Switch between workspaces using
terraform workspace select <name>
. - Apply infrastructure changes specific to each workspace โ each has its own isolated state.
๐ฅ Example Input:
# Create workspaces
terraform workspace new dev
terraform workspace new prod
# Select and apply
terraform workspace select dev
terraform apply
terraform workspace select prod
terraform apply
๐ Expected Output:
Separate infrastructure is deployed for each workspace with independent state tracking.
โ Terraform Workspace Commands:
terraform workspace list
terraform workspace show
terraform workspace new staging
terraform workspace select prod
terraform workspace delete dev
๐ Detailed Explanation:
- State Isolation: Each workspace maintains its own
terraform.tfstate
file. - Multi-Env Management: Easily manage separate environments (dev, staging, prod) without duplicating configuration files.
- Non-Destructive Switching: Switching workspaces doesnโt affect infrastructure in others.
- Scalability: Enables scaling deployments across multiple environments using the same codebase.
๐ ๏ธ Use Cases:
- Managing multiple deployment environments from a single Terraform project.
- Testing infrastructure changes in dev before promoting to prod.
- Facilitating CI/CD pipelines with isolated state for preview environments.
- Reducing human error by isolating changes per workspace.