This article explores using the for_each meta-argument in Terraform to manage resources more reliably than with the count meta-argument.
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.
This configuration creates resources as a list. However, updating resources based on index positions can lead to unexpected behavior when the list order changes.
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:
Copy
Ask AI
$ terraform planError: Invalid for_each argument on main.tf line 2, in resource "local_file" "pet": 2: for_each = var.filenameThe given "for_each" argument value is unsuitable: the "for_each"argument must be a map, or set of strings, and you have provided a valueof type list of string.
Ensure that the data type passed to for_each complies with Terraform’s requirements—a map or a set of strings.
When you run terraform plan now, Terraform will indicate that three resources will be created:
Copy
Ask AI
$ terraform planTerraform will perform the following actions: # local_file.pet["/root/cats.txt"] will be created + resource "local_file" "pet" { + directory_permission = "0777" + file_permission = "0777" + filename = "/root/cats.txt" }...<output trimmed>...Plan: 3 to add, 0 to change, 0 to destroy.
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.
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!