0
0
Terraformcloud~3 mins

Why Dynamic blocks in ingress rules in Terraform? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one block that builds all your firewall rules perfectly every time?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
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
dynamic "ingress" {
  for_each = var.ports
  content {
    from_port   = each.value
    to_port     = each.value
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
What It Enables

You can manage many ingress rules easily and update them all by changing just one list.

Real Life Example

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.

Key Takeaways

Manual ingress rules are repetitive and error-prone.

Dynamic blocks automate rule creation from lists.

This makes Terraform code cleaner and easier to maintain.