0
0
Terraformcloud~3 mins

Why Dynamic block syntax in Terraform? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one block that magically creates many, saving hours of tedious work?

The Scenario

Imagine you need to create many similar resources in your cloud setup, like multiple firewall rules or storage buckets, each with slightly different settings. Doing this by writing each block manually feels like copying and pasting over and over.

The Problem

Manually repeating similar blocks is slow and boring. It's easy to make mistakes like forgetting to change a name or a setting. If you want to add or remove items, you have to edit many places, which wastes time and causes errors.

The Solution

Dynamic block syntax lets you write one flexible block that repeats itself based on your list of items. This means you write less code, avoid mistakes, and can easily change how many blocks you create by just changing your data.

Before vs After
Before
resource "aws_security_group" "example" {
  ingress {
    from_port = 80
    to_port   = 80
    protocol  = "tcp"
    cidr_blocks = ["10.0.0.1/32"]
  }
  ingress {
    from_port = 443
    to_port   = 443
    protocol  = "tcp"
    cidr_blocks = ["10.0.0.2/32"]
  }
}
After
resource "aws_security_group" "example" {
  dynamic "ingress" {
    for_each = var.rules
    content {
      from_port   = ingress.value.from_port
      to_port     = ingress.value.to_port
      protocol    = ingress.value.protocol
      cidr_blocks = [ingress.value.cidr_blocks]
    }
  }
}
What It Enables

You can create many similar infrastructure blocks easily and safely by just changing your input data, making your code cleaner and more flexible.

Real Life Example

When setting up a firewall, you might have dozens of rules for different ports and IPs. Using dynamic blocks, you define all rules in one list and Terraform creates all the needed blocks automatically.

Key Takeaways

Manual repetition is slow and error-prone.

Dynamic blocks let you loop over data to create repeated blocks.

This makes your infrastructure code simpler, safer, and easier to update.