Skip to main content
Terraform·8 min read

Terraform Dynamic Blocks — Generating Repeated Nested Config Without the Copy-Paste

How to use dynamic blocks to generate repeated nested blocks from a list or map, the iterator object, when to choose dynamic blocks over count or for_each, readability tradeoffs, and a realistic security group example.

DT

DevOps Engineer & Technical Writer

The Problem

Some resources contain repeated nested blocks. A security group has one ingress block per rule; an autoscaling group has one tag block per tag. If you have ten ingress rules, the naive approach is to copy the ingress { ... } block ten times. That is tedious, error-prone, and impossible to drive from a variable. Dynamic blocks let you generate those nested blocks from a list or map instead.

A LIST VARIABLE EXPANDS INTO MANY REPEATED NESTED BLOCKS var.ingress_rules (list) { port = 443, cidr = "0.0.0.0/0" } https { port = 80, cidr = "0.0.0.0/0" } http { port = 22, cidr = "10.0.0.0/8" } ssh (internal) dynamic for_each aws_security_group.web ingress { 443 ← 0.0.0.0/0 } ingress { 80 ← 0.0.0.0/0 } ingress { 22 ← 10.0.0.0/8 } one nested block per list element

One variable in, many nested blocks out. Change the list and the generated blocks change with it — no copy-paste.

The Repetition You Want to Avoid

Here is the problem written out longhand. Three rules means three nearly identical blocks:

resource "aws_security_group" "web" {

name = "web"

vpc_id = var.vpc_id

ingress {

from_port = 443

to_port = 443

protocol = "tcp"

cidr_blocks = ["0.0.0.0/0"]

}

ingress {

from_port = 80

to_port = 80

protocol = "tcp"

cidr_blocks = ["0.0.0.0/0"]

}

ingress {

from_port = 22

to_port = 22

protocol = "tcp"

cidr_blocks = ["10.0.0.0/8"]

}

}

Adding a rule means editing the resource. You cannot drive the rules from a variable, and every environment that needs different rules becomes a separate hard-coded copy.

A <code class="inline-code">dynamic</code> Block with <code class="inline-code">for_each</code>

A dynamic block replaces the repeated nested block. Its label (ingress) names the block being generated, for_each supplies the collection, and the content {} block is the template rendered once per element:

variable "ingress_rules" {

type = list(object({

port = number

cidr_block = string

}))

default = [

{ port = 443, cidr_block = "0.0.0.0/0" },

{ port = 80, cidr_block = "0.0.0.0/0" },

{ port = 22, cidr_block = "10.0.0.0/8" },

]

}

resource "aws_security_group" "web" {

name = "web"

vpc_id = var.vpc_id

dynamic "ingress" {

for_each = var.ingress_rules

content {

from_port = ingress.value.port

to_port = ingress.value.port

protocol = "tcp"

cidr_blocks = [ingress.value.cidr_block]

}

}

}

Now the rules live entirely in a variable. Dev, staging, and prod can each pass a different ingress_rules list to the same module.

The Iterator Object: <code class="inline-code">.key</code> and <code class="inline-code">.value</code>

Inside the content block you refer to the current element through an iterator, which by default is named after the block label (ingress here). It exposes two attributes:

  • .value — the current element. For a list it is the element itself; for a map it is the map's value.
  • .key — the index (for a list) or the map key (for a map).

You can rename the iterator with iterator = when nesting dynamic blocks would otherwise collide:

dynamic "ingress" {

for_each = var.ingress_rules

iterator = rule

content {

from_port = rule.value.port

to_port = rule.value.port

protocol = "tcp"

cidr_blocks = [rule.value.cidr_block]

description = "rule-${rule.key}"

}

}

Using a map instead of a list gives you stable, meaningful keys:

variable "ingress_rules" {

type = map(object({ port = number, cidr_block = string }))

default = {

https = { port = 443, cidr_block = "0.0.0.0/0" }

ssh = { port = 22, cidr_block = "10.0.0.0/8" }

}

}

# ingress.key is now "https" / "ssh" — useful for descriptions

Dynamic Blocks vs <code class="inline-code">count</code> vs <code class="inline-code">for_each</code> on a Resource

These three solve different problems — do not confuse them:

ToolRepeatsUse when
<code class="inline-code">dynamic</code> blockA <strong>nested block inside one resource</strong>A single resource needs many repeated inner blocks (ingress rules, tags)
<code class="inline-code">for_each</code> on a resource<strong>Whole resources</strong>, keyedYou need many copies of a resource with stable keys
<code class="inline-code">count</code> on a resource<strong>Whole resources</strong>, by indexYou need N identical copies and index-based addressing is fine

The key distinction: a dynamic block generates blocks within a resource, while count and for_each generate separate resources. If each rule needed to be an independent aws_security_group_rule resource (so you could target one for replacement), you would use for_each on that resource instead.

Readability Tradeoffs

Dynamic blocks are powerful but they obscure the shape of the final resource. A reader can no longer see the actual ingress rules at a glance — they have to mentally expand the loop. Guidelines that keep them maintainable:

  • Use a dynamic block only when the nested block genuinely repeats and the data is variable. For two fixed rules, plain blocks are clearer.
  • Keep the content template small. Complex conditionals inside content are hard to read.
  • Prefer a map over a list when elements have identity, so the plan output and keys are stable.
  • Document the variable's object type so callers know the shape to pass.

Common Mistakes to Avoid

  • Reaching for a dynamic block for two static values. The indirection costs more readability than it saves. Write the blocks out.
  • Using .value where you meant .key (or vice versa). With a list, .key is a numeric index; with a map it is the key string. Pick the collection type that matches what you need.
  • Confusing a dynamic block with for_each on a resource. One repeats inner blocks; the other repeats whole resources. They are not interchangeable.
  • Nesting dynamic blocks without iterator. Two nested dynamics both default their iterator to the block label and can shadow each other. Rename with iterator =.
  • Building giant lists inline in the resource. Define the collection in a variable or local so the resource stays readable and the data is reusable.

FAQ

What is the iterator in a dynamic block?

The iterator is the temporary object representing the current element of the collection as Terraform loops. By default it is named after the block label (so a dynamic "ingress" block uses ingress.value and ingress.key). You can rename it with the iterator argument, which is necessary when nesting dynamic blocks that would otherwise share a name.

When should I use a dynamic block instead of <code class="inline-code">for_each</code> on the resource?

Use a dynamic block when a single resource contains repeated nested blocks — like multiple ingress blocks in one security group. Use for_each on the resource when you want many separate resources, each independently addressable. If you need to target one rule for replacement without touching the others, separate resources via for_each are the better fit.

Can I use a condition to skip generating a block?

Yes. Because for_each drives the dynamic block, you can pass an empty collection to generate zero blocks, or filter the collection beforehand (for example with a for expression) so only matching elements produce a block. An empty list or map simply yields no nested blocks.

Do dynamic blocks hurt readability?

They can. A dynamic block hides the concrete shape of the resource behind a loop, so a reader must expand it mentally. Use them only when the repetition is real and data-driven; for a couple of fixed blocks, plain static blocks are clearer and easier to review.