0
0
Terraformcloud~3 mins

Why dynamic blocks reduce repetition in Terraform - The Real Reasons

Choose your learning style9 modes available
The Big Idea

Discover how one simple feature can save you hours of repetitive work and headaches!

The Scenario

Imagine you need to create many similar parts in your cloud setup, like multiple firewall rules or repeated resource settings. Writing each one by hand means copying and changing the same code again and again.

The Problem

Manually repeating code is slow and tiring. It's easy to make mistakes, like forgetting to update a value or adding inconsistent settings. This can cause errors and waste time fixing them.

The Solution

Dynamic blocks let you write the repeated part just once and tell the system to create many copies with different details automatically. This keeps your code clean, easy to read, and less error-prone.

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 quickly create many similar configurations with less code, making your cloud setup faster and safer to manage.

Real Life Example

When setting up a firewall, instead of writing each rule separately, you use dynamic blocks to generate all needed rules from a list of ports, saving time and avoiding mistakes.

Key Takeaways

Manual repetition wastes time and risks errors.

Dynamic blocks automate repeated code parts.

This leads to cleaner, safer, and faster cloud configurations.