Looping with count and for_each
Traditionally, you can create multiple resources by using the count or for_each arguments:
server1 and server2) are instantiated by leveraging count.
Building a VPC, Subnet, and Security Group
Let’s set up:- A new VPC
- A private subnet
- A security group allowing SSH (port 22) and HTTP (port 8080)
10.0.0.0/16), and the subnet uses 10.0.2.0/24. The security group acts as a virtual firewall.

ingress blocks:
ingress blocks, quickly becoming repetitive.
Simplifying with Dynamic Blocks
With a dynamic block, you can loop over a list of ports and generate as manyingress entries as needed.
Declare an input variable for ports:
You can rename the default iterator (
Example:
ingress) to anything meaningful.Example:
Splat Expressions
After generating multiple ingress rules, you might want to output allto_port values at once. Use a splat expression:
Be aware that splat expressions return a list. If your security group has no
ingress rules, you’ll get an empty list rather than a single value.Compare Approaches
| Approach | Description | Pros |
|---|---|---|
| Static Blocks | Individual ingress blocks for each port | Simple for few ports |
| Dynamic Blocks | One block looping over var.ingress_ports | DRY, maintainable |
| Splat Expressions | Extracts list of attributes from resources | Concise outputs |