Terraform Expressions
Imagine you’re running your Lego city with Terraform. Sometimes you need smart rules:
- “If it’s production, build 5 towers; if it’s dev, build 1.”
- “Take this list of streets and rename them with uppercase letters.”
- “Map each park to a tag that says ‘green-space’.”
Terraform’s expression language gives you the power to write these rules directly in your configuration. With conditionals, loops, and transformations, you can turn static code into adaptive infrastructure logic.
Key Concepts
Conditional Expressions
- Result: Chooses instance type based on environment.
variable "is_prod" {
default = false
}
output "instance_type" {
value = var.is_prod ? "t3.large" : "t2.micro"
}
condition ? true_value : false_value
For Expressions (Loops)
- Transform collections dynamically.
- Result: Creates a map of subnets with tags.
variable "subnets" {
default = ["10.0.1.0/24", "10.0.2.0/24"]
}
output "tags" {
value = { for subnet in var.subnets : subnet => "env-dev" }
}
Complex Data Transformations
Transforming maps:
variable "users" {
default = {
alice = "admin"
bob = "developer"
}
}
output "roles" {
value = { for name, role in var.users : name => upper(role) }
}
→ { alice = "ADMIN", bob = "DEVELOPER" }
Filtering lists:
output "filtered" {
value = [for port in [80, 443, 22] : port if port != 22]
}
→ [80, 443]
Combining Functions with Expressions
- Result: Joins subnets into a single uppercase string.
output "summary" {
value = join(", ", [for subnet in var.subnets : upper(subnet)])
}
Hands‑On Lab / Demo
Lab: Dynamic Environment Configurations
Run terraform apply → Output:Code
replica_counts = {
dev = 1
staging = 2
prod = 5
}
Use expressions:
output "replica_counts" {
value = { for env in var.environments :
env => env == "prod" ? 5 : env == "staging" ? 2 : 1
}
}
Define environments:
variable "environments" {
default = ["dev", "staging", "prod"]
}
Pro Tips & Best Practices
- Use conditionals for environment‑specific logic.
- Use
forexpressions to transform collections cleanly. - Combine functions with expressions for powerful transformations.
- Keep expressions readable - avoid overly complex one‑liners.
- Document transformations in module README for clarity.
Summary & Cheatsheet
- Conditional:
? :for inline logic. - For expressions: Transform lists/maps dynamically.
- Filtering: Use
ifinsideforloops. - Transformations: Combine functions with expressions.
Quick mnemonic: Expressions = Logic + Loops + Transformations
The Hackers Notebook
Terraform expressions are the logic engine of your configurations. They let you apply conditionals, loops, and transformations to make infrastructure adaptive and intelligent. By mastering expressions, you unlock the ability to write concise, powerful, and reusable Terraform code.
