Interview Prep/Terraform/Resources Variables and Expressions

A security group needs 15 ingress rules read from a variable. How do you avoid 15 copy-pasted blocks?

IntermediateScenarioResources Variables and Expressions
Answer

Situation read → Repeated nested blocks: use dynamic.

What I'd do →

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

  dynamic "ingress" {
    for_each = var.ingress_rules   # map(object({port=number, cidrs=list(string)}))
    content {
      description = ingress.key
      from_port   = ingress.value.port
      to_port     = ingress.value.port
      protocol    = "tcp"
      cidr_blocks = ingress.value.cidrs
    }
  }
}

Why → dynamic generates blocks from a collection. For larger rule sets, I prefer separate aws_vpc_security_group_ingress_rule resources so rules have their own state addresses.

Interview tip → Overusing dynamic hurts readability; use it only where the structure is genuinely variable.

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions