Terraform Tutorial — Workspace Interpolation
The built-in terraform.workspace variable returns the name of the current workspace. Use it to differentiate resources across environments.
Basic Usage
resource "aws_s3_bucket" "app" {
bucket = "myapp-${terraform.workspace}-assets"
}
| Workspace | Bucket Name |
|---|---|
| dev | myapp-dev-assets |
| staging | myapp-staging-assets |
| prod | myapp-prod-assets |
Conditional Sizing
Use workspace names to control resource sizes:
locals {
instance_types = {
dev = "t3.micro"
staging = "t3.small"
prod = "t3.large"
}
instance_counts = {
dev = 1
staging = 2
prod = 5
}
}
resource "aws_instance" "web" {
count = local.instance_counts[terraform.workspace]
ami = data.aws_ami.amazon_linux.id
instance_type = local.instance_types[terraform.workspace]
tags = {
Name = "web-${terraform.workspace}-${count.index + 1}"
Environment = terraform.workspace
}
}
Tagging with Workspace
locals {
common_tags = {
Environment = terraform.workspace
ManagedBy = "terraform"
Project = "myapp"
}
}
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
tags = merge(local.common_tags, {
Name = "myapp-${terraform.workspace}-vpc"
})
}
Backend Key with Workspace
Remote backends automatically separate state by workspace:
# S3 backend stores state at:
# s3://bucket/env:/dev/terraform.tfstate
# s3://bucket/env:/staging/terraform.tfstate
# s3://bucket/env:/prod/terraform.tfstate
What’s Next?
Workspaces aren’t always the right tool. Let’s compare workspaces vs separate directories.