Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

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:

  1. Initialize your Terraform project using terraform init.
  2. Create a new workspace using terraform workspace new <name>.
  3. Switch between workspaces using terraform workspace select <name>.
  4. 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.