Interview Prep/Real-World Interview/Write-Terraform tasks

Write a dynamic block that creates ingress rules from a variable list.

IntermediateHands-onWrite-Terraform tasks
Answer
variable "ingress" {
  type = list(object({ port = number, cidr = string, desc = string }))
  default = [
    { port = 80,  cidr = "0.0.0.0/0",   desc = "http"  },
    { port = 443, cidr = "0.0.0.0/0",   desc = "https" },
    { port = 22,  cidr = "10.0.0.0/8",  desc = "ssh internal" },
  ]
}

resource "aws_security_group" "app" {
  name   = "app"
  vpc_id = var.vpc_id

  dynamic "ingress" {
    for_each = var.ingress
    content {
      description = ingress.value.desc
      from_port   = ingress.value.port
      to_port     = ingress.value.port
      protocol    = "tcp"
      cidr_blocks = [ingress.value.cidr]
    }
  }
}

Key trick → Inside content, the iterator is named after the block (ingress.value). Use dynamic blocks sparingly, because they hurt readability.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-Terraform tasks