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:main.tf:
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:
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 withcount form a list. To view the ID of the second element (index 1):
id attribute in the output.
Task 4: Parameterize with Variables and count
Define variables in variables.tf:
main.tf:
users element becomes a filename. Initialize and apply:
Task 5: Set Default Values for Variables
Add sensible defaults invariables.tf:
- Type of
users:list(string) - List vs. set: Lists allow duplicates; sets do not.
Task 6: Ensure Unique Instances with for_each
Refactor main.tf to use for_each on a set:
toset() function removes duplicates, and for_each creates a map keyed by each unique filename.
Initialize and apply:
- Eliminates duplicates automatically
- Creates a map, so you can reference resources by key:
local_sensitive_file.name["/root/user11"]
Comparing count vs. for_each
| Feature | count | for_each |
|---|---|---|
| Data structure | List (indexed) | Map (keyed by value) |
| Handling duplicates | Requires manual deduplication | Automatic when using toset() |
| Reference syntax | resource.name[0] | resource.name["key"] |
Q&A
-
What data structure does
for_eachproduce?
A map, keyed by each unique element. -
How do you address the resource for
/root/user11withfor_each?
local_sensitive_file.name["/root/user11"]