0
0
Terraformcloud~30 mins

Why workspaces separate environments in Terraform - See It in Action

Choose your learning style9 modes available
Why Workspaces Separate Environments in Terraform
📖 Scenario: You are managing cloud infrastructure using Terraform. You want to keep your development and production environments separate to avoid accidental changes and to manage resources safely.
🎯 Goal: Build a Terraform configuration that uses workspaces to separate dev and prod environments, showing how to create and switch workspaces and use workspace-specific variables.
📋 What You'll Learn
Create a Terraform configuration with a resource that uses workspace-specific naming
Create two workspaces named dev and prod
Use a variable that changes based on the current workspace
Show how to switch between workspaces
💡 Why This Matters
🌍 Real World
Separating environments like development, staging, and production is critical in cloud infrastructure to prevent accidental resource changes and to test safely.
💼 Career
Cloud engineers and DevOps professionals use Terraform workspaces to manage multiple environments efficiently and safely.
Progress0 / 4 steps
1
Create a Terraform configuration with a variable for environment
Create a Terraform file named main.tf with a variable called environment of type string and default value dev. Also, define a resource aws_s3_bucket named my_bucket that uses the environment variable in its bucket name as my-bucket-${environment}.
Terraform
Need a hint?

Use variable block to define environment and use var.environment inside the resource.

2
Create Terraform workspaces for dev and prod environments
Add instructions in a comment in main.tf to create two Terraform workspaces named dev and prod using the command terraform workspace new. Also add a comment showing how to list workspaces with terraform workspace list.
Terraform
Need a hint?

Use comments starting with # to add the workspace commands.

3
Use Terraform workspace to set environment variable dynamically
Modify main.tf to remove the default value of environment variable. Instead, create a local variable called current_env that uses the Terraform workspace name with terraform.workspace. Then update the aws_s3_bucket resource to use current_env for the bucket name.
Terraform
Need a hint?

Use locals block to define current_env as terraform.workspace.

4
Switch between workspaces and apply configuration
Add comments in main.tf showing how to switch to the prod workspace using terraform workspace select prod and how to apply the configuration with terraform apply. This completes the setup to separate environments using workspaces.
Terraform
Need a hint?

Use comments to show the commands for switching workspace and applying.