What if you could write your cloud setup once and have Terraform fill in all the repeated details perfectly every time?
Dynamic blocks vs for_each decision in Terraform - When to Use Which
Imagine you need to create many similar parts in your cloud setup, like multiple firewall rules or repeated resource settings. Doing this by copying and pasting code for each part feels like writing the same email over and over again.
Manually repeating code is slow and easy to mess up. If you want to change something, you must update every copy, risking mistakes and wasting time. It's like juggling many balls and dropping some.
Using dynamic blocks and for_each in Terraform lets you write the repeated parts just once. Terraform then automatically creates all the needed pieces based on your list or map. This saves time, reduces errors, and keeps your setup neat.
resource "aws_security_group" "example" { 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"] } }
resource "aws_security_group" "example" { dynamic "ingress" { for_each = [80, 443] content { from_port = ingress.value to_port = ingress.value protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } } }
You can easily create many similar cloud settings by changing just your input list, making your infrastructure flexible and error-free.
When setting up a web server, you might want to open ports 80 and 443 for HTTP and HTTPS. Instead of writing two blocks, you use dynamic blocks or for_each to generate both automatically.
Manual repetition is slow and risky.
Dynamic blocks and for_each automate repeated parts.
This leads to cleaner, safer, and easier-to-change cloud setups.