Dynamic Blocks for Nested Configuration
Generate repeated nested configuration blocks programmatically using dynamic blocks, eliminating copy-paste for things like security group rules.
The Repetition Problem
Some resources contain repeated nested blocks, such as multiple ingress rules in a security group. Writing each by hand is verbose and hard to keep DRY. Dynamic blocks generate them from a collection.
Static Blocks First
Here is the manual version: three near-identical ingress blocks. Imagine maintaining a dozen of these.
resource "aws_security_group" "web" {
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}All lessons in this course
- Using Loops with `for_each` and `count`
- Terraform Built-in Functions
- Conditional Expressions and Splats
- Dynamic Blocks for Nested Configuration