Terraform · Infrastructure as code
How do dynamic blocks work and when should you avoid them?
Short answer
A dynamic block generates repeated nested blocks from a collection. It reduces duplication for things like security group rules, but it hurts readability, so keep the generated shape simple and prefer for_each at the resource level.
Some provider schemas use repeated nested blocks rather than a separate resource. A dynamic block iterates a collection and generates one block per item. The iterator name defaults to the block label, and each generated block can reference iterator.value and iterator.key.
variable "ingress_rules" {
type = map(object({
from_port = number
to_port = number
cidr = string
}))
}
resource "aws_security_group" "app" {
name = "app-sg"
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = "tcp"
cidr_blocks = [ingress.value.cidr]
}
}
}When dynamic blocks help
- Repeated nested blocks such as ingress rules or environment variables
- Optional nested blocks driven by a list or map
- A provider schema that offers no separate resource for the item
Dynamic blocks cannot generate meta-arguments, provider blocks or top-level arguments. They also make plans harder to read because the generated structure is implicit. If the collection is large or the content complex, a separate resource or a small module is often clearer and easier to test.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the default iterator name for a dynamic block?
- 2Can a dynamic block generate a provider configuration?
- 3When is a separate resource clearer than a dynamic block?
- 4How do you make generated rules stable across changes?
Say it in the interview
A dynamic block generates repeated nested blocks from a collection, which is useful for things like security group rules where the provider schema expects inline blocks. I give the collection stable keys so the plan is readable. I avoid deep nesting and do not use dynamic blocks for meta-arguments or providers, because they cannot generate those. When the structure gets complex, a separate resource or module is clearer.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Terraform mock interview and get scored feedback on depth, clarity and confidence.