Terraform Tutorial — Workspaces Practice Exercises

1 minute read

Practice managing Terraform workspaces.


Exercise 1: Create and Switch

Task: Create workspaces for dev, staging, and prod. Then switch to the staging workspace and verify.

Answer
$ terraform workspace new dev
$ terraform workspace new staging
$ terraform workspace new prod
$ terraform workspace select staging
$ terraform workspace show
staging

Exercise 2: Workspace-Aware Naming

Task: Write an S3 bucket resource that includes the workspace name, producing myapp-dev-logs, myapp-staging-logs, or myapp-prod-logs.

Answer
resource "aws_s3_bucket" "logs" {
  bucket = "myapp-${terraform.workspace}-logs"

  tags = {
    Environment = terraform.workspace
  }
}

Exercise 3: Conditional Sizing

Task: Write a locals block that maps workspace names to instance types: dev→t3.micro, staging→t3.small, prod→t3.large.

Answer
locals {
  instance_types = {
    dev     = "t3.micro"
    staging = "t3.small"
    prod    = "t3.large"
  }
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.amazon_linux.id
  instance_type = local.instance_types[terraform.workspace]
}

Exercise 4: Workspaces vs Directories

Task: Your company has dev and prod environments. Dev uses 1 AZ and no NAT gateway. Prod uses 3 AZs, NAT gateways, and a WAF. Should you use workspaces or directories? Explain why.

Answer

Use directories. The environments are significantly different — different number of AZs, different services (NAT, WAF). Workspaces work best when environments are nearly identical and differ only in size/count. With directories, each environment has its own configuration that clearly reflects its architecture.


Chapter Summary

In this chapter, you learned:

  • Workspaces create isolated state for the same configuration
  • Commands: new, select, list, show, delete
  • terraform.workspace returns the current workspace name for dynamic config
  • Use locals maps for workspace-aware sizing and naming
  • Workspaces = same config, different sizes. Directories = different configs entirely
  • Remote backends automatically separate state by workspace

Next up: Backends — configuring remote state storage.


← Multi-Environment Pattern Backends →