0
0
Terraformcloud~3 mins

Dynamic blocks vs for_each decision in Terraform - When to Use Which

Choose your learning style9 modes available
The Big Idea

What if you could write your cloud setup once and have Terraform fill in all the repeated details perfectly every time?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
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"]
  }
}
After
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"]
    }
  }
}
What It Enables

You can easily create many similar cloud settings by changing just your input list, making your infrastructure flexible and error-free.

Real Life Example

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.

Key Takeaways

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.