count and for_each repeat whole resources. But many resources have nested blocks inside them that you may need a variable number of: a container’s ports and volumes, a security group’s rules, a load balancer’s listeners. A dynamic block generates those nested blocks from a collection.
The problem
Each Orbit environment publishes different ports. Dev exposes the web app, the API and a debugger; staging exposes only the web app. Written by hand, the container looks like this:
resource "docker_container" "web" {
name = "orbit-dev-web"
image = docker_image.web.image_id
ports {
internal = 80
external = 8080
}
ports {
internal = 9090
external = 9090
}
ports {
internal = 9229
external = 9229
}
}
You cannot put count on a ports block, and copying the resource per environment defeats the purpose of variables.
A dynamic block
Describe the ports as data:
variable "published_ports" {
type = list(object({
internal = number
external = number
protocol = optional(string, "tcp")
}))
default = [
{ internal = 80, external = 8080 },
]
}
Then generate one ports block per item:
resource "docker_container" "web" {
name = "orbit-${var.environment}-web"
image = docker_image.web.image_id
dynamic "ports" {
for_each = var.published_ports
content {
internal = ports.value.internal
external = ports.value.external
protocol = ports.value.protocol
}
}
}
# dev.tfvars
published_ports = [
{ internal = 80, external = 8080 },
{ internal = 9090, external = 9090 },
{ internal = 9229, external = 9229 },
]
How to read it:
- The label after
dynamic("ports") is the name of the nested block to generate. for_eachtakes any list, set or map; one block is generated per element.- Inside
content, the iterator is named after the block:ports.key(index for lists, key for maps) andports.value(the element).
If the name ports.value is confusing, rename the iterator:
dynamic "ports" {
for_each = var.published_ports
iterator = p
content {
internal = p.value.internal
external = p.value.external
}
}
Volumes from a map
The same pattern mounts a variable set of volumes. A map gives each mount a meaningful key:
variable "mounts" {
type = map(object({
container_path = string
read_only = optional(bool, false)
}))
default = {
uploads = { container_path = "/var/lib/orbit/uploads" }
config = { container_path = "/etc/orbit", read_only = true }
}
}
resource "docker_volume" "orbit" {
for_each = var.mounts
name = "orbit-${var.environment}-${each.key}"
}
resource "docker_container" "api" {
name = "orbit-${var.environment}-api"
image = docker_image.api.image_id
dynamic "volumes" {
for_each = var.mounts
content {
volume_name = docker_volume.orbit[volumes.key].name
container_path = volumes.value.container_path
read_only = volumes.value.read_only
}
}
}
Note how the dynamic block and the for_each resource share the same map, so each mount finds its volume by key.
Optional nested blocks
A dynamic block over an empty collection generates nothing, which makes it the standard way to add a nested block only sometimes. Orbit’s API gets a health check everywhere except dev:
variable "healthcheck_enabled" {
type = bool
default = true
}
resource "docker_container" "api" {
# ...
dynamic "healthcheck" {
for_each = var.healthcheck_enabled ? [1] : []
content {
test = ["CMD", "wget", "-qO-", "http://localhost:9090/healthz"]
interval = "10s"
timeout = "3s"
retries = 3
}
}
}
The [1] is a one-element list whose content does not matter: it only says “generate the block once”.
Nested dynamic blocks
Dynamic blocks can contain dynamic blocks, for resources with blocks inside blocks. It works, and it is also where readability falls off a cliff. If you find yourself writing rule.value.ports.value, step back and see if separate resources would be clearer.
When not to use a dynamic block
Dynamic blocks hide the structure of a resource behind data, which makes code harder to read and plans harder to review. Some guidelines:
- Static blocks stay static. If a container always has exactly one port, write the
portsblock by hand. - Prefer separate resources when the provider offers them. Many providers now model sub-objects as their own resources. On AWS, inline
ingressandegressblocks inaws_security_groupare discouraged; useaws_vpc_security_group_ingress_rulewithfor_eachinstead. Each rule gets its own address, its own plan line and can be changed without touching the others:
resource "aws_security_group" "web" {
name = "orbit-${var.environment}-web"
vpc_id = var.vpc_id
}
resource "aws_vpc_security_group_ingress_rule" "web" {
for_each = { https = 443, http = 80 }
security_group_id = aws_security_group.web.id
cidr_ipv4 = "0.0.0.0/0"
ip_protocol = "tcp"
from_port = each.value
to_port = each.value
description = "Allow ${each.key}"
}
- Dynamic blocks cannot generate meta-argument blocks such as
lifecycleorprovisioner, and they cannot generate top-levelresourceblocks: that is whatfor_eachon the resource is for.
Quick reference
| Task | Syntax |
|---|---|
| Repeat a nested block | dynamic "ports" { for_each = ... content { ... } } |
| Current element | ports.value |
| Current index or key | ports.key |
| Rename the iterator | iterator = p, then p.value |
| Block only when a flag is on | for_each = var.enabled ? [1] : [] |
| Block only when a value is set | for_each = var.tls == null ? [] : [var.tls] |
| Separate rule resources (AWS) | aws_vpc_security_group_ingress_rule with for_each |
Exercise
Inside dynamic “volumes” { for_each = var.mounts … }, where var.mounts is a map, how do you read the current map key?
Show answer
Answer: B. In a dynamic block the iterator is named after the block label (or the iterator argument), so it is volumes.key and volumes.value. each.key belongs to for_each on a resource or module.
Exercise
A container needs a healthcheck block only in staging and prod. What is the usual way to write that?
Show answer
Answer: B. Nested blocks do not accept count. A dynamic block over a one-element or empty list generates the block once or not at all.
Key takeaways
- Dynamic blocks generate repeated nested blocks;
for_eachon the resource repeats whole resources. - The iterator is named after the block:
ports.keyandports.value, or rename it withiterator. - An empty collection generates nothing:
var.enabled ? [1] : []makes a block optional. - Share one map between a
for_eachresource and a dynamic block to link items by key. - Prefer separate resources (like
aws_vpc_security_group_ingress_rule) when the provider offers them. - Keep static blocks static: dynamic blocks cost readability.
FAQ
Can a dynamic block use a list of strings?
Yes. for_each accepts lists, sets and maps; with a list of strings, x.value is each string and x.key its index.
Why does my plan replace the whole resource when I add one item to a dynamic block?
That depends on the provider: some nested blocks can only be set at creation time. Docker container ports, for example, force a new container. Check the plan for # forces replacement before applying.
Can I use a dynamic block in a provider or terraform block?
Inside provider configuration blocks, yes, for their nested blocks. In the terraform block (backend, required_providers), no: those are read before any expressions are evaluated.
Is a deeply nested dynamic block a code smell?
Usually. Two levels is the practical limit for readability. Beyond that, split the configuration into separate resources or a small module.