Using count with a List
Traditionally, resources are created using the count meta-argument. For example:Transitioning to for_each
Switching to for_each can help manage resources more effectively by assigning a unique key to each resource using each.value. An initial attempt might be:terraform plan with this configuration results in an error. The for_each argument only supports a map or a set of strings – not a list of strings. The error message appears similar to:
Ensure that the data type passed to for_each complies with Terraform’s requirements—a map or a set of strings.
Correcting the Configuration
There are two approaches to resolve this issue:- Change the variable type from a list to a set (sets do not allow duplicate elements).
- Convert the list into a set in the resource block using Terraform’s built-in
tosetfunction.
toset function:
terraform plan now, Terraform will indicate that three resources will be created:
Updating Resources by Removing an Element
Let’s simulate updating the configuration by removing an element. For example, removing/root/pets.txt from the list changes the configuration to:
terraform plan with this updated variable shows that only the resource associated with /root/pets.txt will be destroyed:
Outputting Resource Details
To visualize how Terraform manages resources using for_each, you can create an output variable that displays the resource details. Resources managed with for_each are stored as a map, keyed by their unique identifier—in this case, the filename.Using for_each allows the resources to be identified by a unique key (here, the filename), reducing the risk of accidental shifts in resource management compared to using count.