What if you could write one block that builds all your firewall rules perfectly every time?
Why Dynamic blocks in ingress rules in Terraform? - Purpose & Use Cases
Imagine you have to write firewall rules for many servers, each needing different ports open. You write each rule by hand in your Terraform files, repeating similar blocks over and over.
Manually writing each ingress rule is slow and boring. If you need to change a port or add a new rule, you must update many places, risking mistakes and inconsistencies.
Dynamic blocks let you write one flexible block that creates many ingress rules automatically from a list. This saves time and keeps your code clean and easy to update.
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"]
}dynamic "ingress" { for_each = var.ports content { from_port = each.value to_port = each.value protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } }
You can manage many ingress rules easily and update them all by changing just one list.
A company needs to open different ports for web, database, and monitoring servers. Using dynamic blocks, they define all ports in one place and Terraform creates all rules automatically.
Manual ingress rules are repetitive and error-prone.
Dynamic blocks automate rule creation from lists.
This makes Terraform code cleaner and easier to maintain.