Dynamic blocks

Intermediate · 11 min

Generate repeated nested blocks, such as security group rules, from a map or list with a dynamic block, and learn when plain repeated blocks read better.

Before thiscount and for_each

DevOps with Flavius · 11 min

Dynamic blocks

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DevOps with FlaviusReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `count` and `for_each` repeat a whole resource. A `dynamic` block repeats a nested block inside one resource, such as an `ingress` rule.
  • Inside `dynamic "name"`, `for_each` supplies the collection and `content { ... }` is the block to generate, reading `name.value` and `name.key`.
  • The iterator variable is named after the block label by default, and `iterator = x` renames it.
  • A dynamic block can only generate nested blocks, not arguments or meta-arguments such as `count` or `lifecycle`.
  • If there are two or three fixed blocks, write them out. Dynamic blocks earn their place when the list comes from a variable.

One resource, a hundred rules

A security group has a handful of ingress rules. In the provider’s schema they are not separate resources but nested blocks, repeated inside the group. For a single service you write three ingress { ... } blocks by hand and are done. Then a platform team wants one module that serves every service, each with its own list of ports. The number of nested blocks is now data, and HCL’s block syntax has no loop.

for_each on the resource would create a new security group per rule, which is wrong. You need repetition inside one resource, and that is the job of a dynamic block.

The shape

Written from the Terraform docs and not run:

variable "ingress_rules" {
  type = map(object({
    port  = number
    cidrs = list(string)
  }))
}

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.cidrs
    }
  }
}

Three parts:

  • the label, "ingress", says which nested block to generate,
  • for_each is the collection to loop over, same rules as the resource-level one,
  • content holds the body of each generated block.

Inside content, the current element is available under the block’s label: ingress.value and ingress.key. With a list, the key is the index. With a map, it is the map key. If you want a different name, iterator = rule renames it.

What it expands to

To check I understood the expansion, I wrote a small stand-in that does what Terraform does conceptually, turning each entry into a concrete block. It runs on made-up rules and is not Terraform:

  ingress { # http
    from_port = 80
    cidr_blocks = ["0.0.0.0/0"]
  }
  ingress { # ssh
    from_port = 22
    cidr_blocks = ["10.0.0.0/8"]
  }
  ingress { # metrics
    from_port = 9100
    cidr_blocks = ["10.0.0.0/8"]
  }

Three map entries became three nested blocks. After this expansion, the provider sees exactly what it would have seen if you had typed them. The dynamic block is purely a code-generation step inside the language. Add a fourth entry to the map and a fourth block appears, with no change to the resource.

Limits

  • It generates nested blocks only. You cannot generate a plain argument with it, and the docs say it is not possible to generate meta-argument blocks such as lifecycle and provisioner.
  • Nested dynamic blocks are allowed, though the video’s last chapter on them already shows how quickly they become hard to follow.
  • The collection needs to be known at plan time, the same limit as for_each on resources.

When it is the wrong tool

The docs themselves warn that overuse of dynamic blocks makes configuration hard to read, and advise writing nested blocks out literally where possible. Some signs you are overusing them:

  • Three fixed rules. Write three ingress blocks. Someone reading the file sees the policy directly.
  • Blocks that differ in structure, not just values. If each entry needs a different set of arguments, a single content block ends up full of conditionals.
  • Resources that exist as standalone types. Many providers moved rules out into separate resources, such as aws_vpc_security_group_ingress_rule. A separate resource with for_each gives each rule a stable address, and you avoid the all-in-one-object update. I only know this from the AWS provider’s resource list and did not read its recommendation, so check the docs for your provider before deciding.

Remember the lesson from count and for_each: addresses matter. Nested blocks inside one resource have no address of their own. Terraform sees the whole list change as one update to the group, which for a firewall means a brief window while rules are replaced. Separate resources avoid that.

Reading them in the wild

I looked at the AWS VPC module’s main.tf again and counted dynamic " lines: 5 in a 1,549-line file, against roughly 70 count lines. A well-designed public module uses them sparingly, and for exactly the nested-block cases above.

$ grep -c 'dynamic "' main.tf
5

About the video

The embed is all of DevOps with Flavius’s “Terraform Dynamic Blocks: The Secret to Scalable Infrastructure”, July 2025, about 11 minutes. The chapters are “Static block issues”, “How to write Dynamic Blocks”, “YAML Dynamic Blocks” and “Nested Dynamic Blocks”. The description says the example is an AWS security group driven by variables and YAML files. I judged the content from those, and did not check the claims in it. English was judged from title, channel and the English auto-caption track.

Where this fits

You can now generate structure. The other thing configurations generate is text: user-data scripts, config files and policies. That is the next lesson, templates and templatefile.

Check yourself

  1. 01You have one `aws_security_group` and want a rule per entry in `var.ingress_rules`. Why not `for_each` on the resource?

    That would create many security groups. The rules are nested blocks inside one group, so you need a `dynamic "ingress"` block inside it.

  2. 02In `dynamic "ingress" { for_each = var.rules ... }`, what is the name of the current element?

    `ingress`, the block's label. You read `ingress.value` and `ingress.key`. Set `iterator = rule` to call it `rule` instead.

  3. 03Can a dynamic block generate a `lifecycle` block?

    No. Meta-argument blocks such as `lifecycle` and `provisioner` cannot be generated. Dynamic blocks are for nested blocks defined by the resource's provider.

  4. 04When is a dynamic block worse than writing the blocks out?

    When the set is small and fixed. A reader can see three explicit rules at a glance, but has to mentally run a loop to see the same three behind a dynamic block.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark