Skip to main content
In this lesson, we explore the powerful for_each meta-argument in Terraform. By using for_each, you can overcome some limitations of the count meta-argument and manage resources more reliably.

Using count with a List

Traditionally, resources are created using the count meta-argument. For example:
This configuration creates resources as a list. However, updating resources based on index positions can lead to unexpected behavior when the list order changes.

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:
Running 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:
  1. Change the variable type from a list to a set (sets do not allow duplicate elements).
  2. Convert the list into a set in the resource block using Terraform’s built-in toset function.
Below is an updated configuration that uses the toset function:
When you run 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:
Running terraform plan with this updated variable shows that only the resource associated with /root/pets.txt will be destroyed:
The remaining resources persist without change.

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.
Running the output command displays the resources keyed by their filenames:
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.

Conclusion

This lesson demonstrated how to implement the for_each meta-argument in Terraform to manage resources more reliably. By converting a list of strings to a set (either via variable type modification or the toset function), you can efficiently track and update resources using a map keyed by unique identifiers. This approach minimizes errors during deletion or updates compared to using the count meta-argument. Now that you’re familiar with for_each, try practicing these concepts in your Terraform projects to streamline your infrastructure management. Happy coding!

Watch Video

Practice Lab