Skip to main content
In this guide, we’ll explore how to streamline repetitive Terraform configurations in OpenTofu using dynamic blocks and splat expressions. You’ll learn to replace verbose nested blocks with a DRY, scalable approach, and extract attributes efficiently from generated resources.

Looping with count and for_each

Traditionally, you can create multiple resources by using the count or for_each arguments:
Here, two EC2 instances (server1 and server2) are instantiated by leveraging count.

Building a VPC, Subnet, and Security Group

Let’s set up:
  1. A new VPC
  2. A private subnet
  3. A security group allowing SSH (port 22) and HTTP (port 8080)
A VPC provides an isolated network (10.0.0.0/16), and the subnet uses 10.0.2.0/24. The security group acts as a virtual firewall.
The image is a diagram of an Amazon VPC setup, showing a private subnet with two servers (server1 and server2) and a security group allowing inbound traffic on ports 8080 and 22.
First, declare the VPC and subnet:
Next, define a security group with two hard-coded ingress blocks:
Adding more ports would require additional nested ingress blocks, quickly becoming repetitive.

Simplifying with Dynamic Blocks

With a dynamic block, you can loop over a list of ports and generate as many ingress entries as needed. Declare an input variable for ports:
Replace the static blocks with one dynamic block:
You can rename the default iterator (ingress) to anything meaningful.
Example:

Splat Expressions

After generating multiple ingress rules, you might want to output all to_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

ApproachDescriptionPros
Static BlocksIndividual ingress blocks for each portSimple for few ports
Dynamic BlocksOne block looping over var.ingress_portsDRY, maintainable
Splat ExpressionsExtracts list of attributes from resourcesConcise outputs

Apply and Inspect

Execute your plan:
Retrieve the generated ports:
By leveraging dynamic blocks and splat expressions, your OpenTofu configurations become more expressive, concise, and easier to maintain.

References

Watch Video