Back to course

Dynamic Blocks: Handling Repeating Config

Infrastructure as Code (Terraform & OpenTofu Mastery)

Clean Security Groups

If you have 10 inbound ports to open, don't write 10 ingress blocks. Use dynamic.

hcl resource "aws_security_group" "allow_web" { dynamic "ingress" { for_each = [80, 443, 8080] content { from_port = ingress.value to_port = ingress.value protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } } }

This generates the blocks automatically based on your list.