Interview › Infrastructure as Code (Terraform, Ansible)
What is a dynamic block, and when would you use it?
Infrastructure as Code (Terraform, Ansible) · Basic level
Answer
A dynamic block generates repeatable nested blocks inside a resource. I use it when a resource needs zero or more nested blocks based on input, such as security group ingress rules, listener rules, EBS block devices, or Kubernetes container ports. It should not be overused when simple explicit blocks are clearer.
Technical explanation
dynamic blocks generate nested configuration blocks, not top-level resources.
Use them when input data drives repeated nested structures.
Keep them simple; too many dynamic layers make modules hard to read and debug.
Keep Terraform's ownership boundary clear: one state should own a resource or field, and other tools should consume published outputs instead of modifying it.
Use fmt, validate, linting, policy checks, plan review, and state locking before production applies.
Design for small blast radius by splitting state around lifecycle, permissions, and recovery boundaries.
Hands-on example
1. Model repeated resources for: What is a dynamic block, and when would you use it?
2. Prefer stable keys with for_each:
variable "subnets" {
type = map(object({ cidr = string, az = string }))
}
resource "aws_subnet" "private" {
for_each = var.subnets
vpc_id = aws_vpc.main.id
cidr_block = each.value.cidr
availability_zone = each.value.az
tags = { Name = "private-${each.key}" }
}3. For nested blocks, use dynamic only when the input list genuinely drives repeated nested configuration:
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 }
}4. Remove one key and run plan; confirm only that keyed instance is affected rather than later list indexes shifting.
Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Infrastructure as Code (Terraform, Ansible) interview questions
- What problem does for_each solve that count creates when removing items?
- What is the difference between a data source and a resource?
- What is the difference between count and for_each, and when do you use each?
- What is terraform import, and when do you need it?
- What are input variables, outputs, and locals?
- What is configuration drift, and how does Terraform detect it?
- What is the difference between a root module and a child module?
- How do you handle resources changed manually outside Terraform?