Skip to main content
InterviewHubPRO
Section Overview
Q13

Question 13 of 50

Part 1: Terraform Core Architecture, HCL & Providers (1 - 15)

26%
Terraform & IaC (50 Qs)•Part 1: Terraform Core Architecture, HCL & Providers (1 - 15)

How do Dynamic Blocks work in Terraform, and when should you use them?

senior LevelCode ExampleFormsCI/CD & DevOpsSystem Design

In Simple Words: A dynamic block produces repeated nested configuration blocks (like ingress rules inside a security group) inside a top-level resource, driven by a collection variable.

hcl
variable "ingress_ports" {
  type    = list(number)
  default = [80, 443, 8080]
}

resource "aws_security_group" "web" {
  name   = "web-rules"
  vpc_id = aws_vpc.main.id

  dynamic "ingress" {
    for_each = var.ingress_ports
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}