You need to dynamically generate a list of security group ingress rules from a variable. Which HCL construct is correct?

Direct Answer (Verified)Reviewed by Sunny (Senior Cloud Engineer)

Correct Answer: Use a `dynamic "ingress"` block with `for_each` iterating over the variable

`dynamic` blocks in HCL allow you to generate repeated nested blocks (like `ingress`, `egress`, `tag`) programmatically. Example: `dynamic "ingress" { for_each = var.ingress_rules;...

Real Exam Scenario

You need to dynamically generate a list of security group ingress rules from a variable. Which HCL construct is correct?

✓ Correct Answer & Explanation

Correct Answer

Use a `dynamic "ingress"` block with `for_each` iterating over the variable

Why This Answer Is Correct

`dynamic` blocks in HCL allow you to generate repeated nested blocks (like `ingress`, `egress`, `tag`) programmatically. Example: `dynamic "ingress" { for_each = var.ingress_rules; content { from_port = ingress.value.from_port; ... } }`. This avoids duplicating block definitions and supports variable-length rule sets. `count` cannot be used inside nested blocks directly.