Dynamic Blocks and For Expressions
What you'll learn: How to programmatically generate repeating nested configuration blocks without copy-pasting code.
The Core Idea
In Terraform, some resources require nested blocks that look similar but have different values. Imagine a security group with multiple ingress rules, or an IAM policy with several permissions. Instead of copy-pasting blocks and manually changing values, dynamic blocks let you loop through a collection and generate these nested blocks on the fly. Combined with for expressions, you can also transform data structures (like converting a list to a map) to feed into your dynamic blocks.
Why This Matters
When you need 5 ingress rules that differ only by port number, writing 5 separate ingress blocks is tedious and error-prone. Dynamic blocks solve this by iterating over a variable—like a list of ports—and generating each block automatically.
For expressions (which you've seen for iteration) work hand-in-hand here, letting you reshape data before passing it into a dynamic block or resource attribute.
How It Works
A dynamic block uses a special syntax:
dynamic "ingress" {
for_each = var.allowed_ports
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
}
}
Each iteration creates an ingress block. The iterator name (ingress here) lets you reference ingress.value or ingress.key inside the content block.
Key Takeaway:
Dynamic blocks eliminate repetitive nested blocks by looping over collections, while for expressions reshape data—together, they make your configurations flexible and DRY (Don't Repeat Yourself).