Skip to main content
In this lab, you’ll learn how to leverage the count and for_each meta-arguments to create multiple resource instances dynamically in OpenTofu. We’ll work through a series of tasks:
  • Inspecting a basic configuration
  • Scaling with count
  • Parameterizing with variables
  • Ensuring uniqueness with for_each

Task 1: Inspect the Base Configuration

Navigate to your project directory:
Open the default main.tf:
Since there’s only one resource block, running opentofu plan would create one file at /root/user-data.

Task 2: Create Multiple Instances with count

Add the count argument to generate three instances:
Initialize and preview:
Expected plan excerpt:
Apply the changes:
All three instances target the same filepath, so you end up with just one actual file on disk.
Although Terraform plans three resources, they all write to /root/user-data. Use unique filenames or a loop index to avoid overwriting.

Task 3: Accessing Resources by Index

Resources managed with count form a list. To view the ID of the second element (index 1):
Look for the id attribute in the output.

Task 4: Parameterize with Variables and count

Define variables in variables.tf:
Update main.tf:
Now each users element becomes a filename. Initialize and apply:

Task 5: Set Default Values for Variables

Add sensible defaults in variables.tf:
Key points:
  • Type of users: list(string)
  • List vs. set: Lists allow duplicates; sets do not.
Example of a duplicate in a list (invalid for a set):

Task 6: Ensure Unique Instances with for_each

Refactor main.tf to use for_each on a set:
The toset() function removes duplicates, and for_each creates a map keyed by each unique filename. Initialize and apply:
Expected output:
  • Eliminates duplicates automatically
  • Creates a map, so you can reference resources by key:
    local_sensitive_file.name["/root/user11"]

Comparing count vs. for_each


Q&A

  1. What data structure does for_each produce?
    A map, keyed by each unique element.
  2. How do you address the resource for /root/user11 with for_each?
    local_sensitive_file.name["/root/user11"]

Further Reading

That’s a wrap for this lab. Happy automating!

Watch Video

Practice Lab