-In this lecture,
we will take a look at the for_each meta argument
and its uses in Terraform.
In the previous lecture, we saw that when we use count,
the resources are created as a list,
and this can have undesirable results when updating them.
One way to overcome this
is to make use of the for_each argument insert of count,
like this.
Next, to set the value of file name to each element in the list,
we can make use of the expression is.value like this.
However, there's a catch.
If we run Terraform plan now,
we will see an error.
The for_each argument only works with a map or a set.
In the variables.tf file,
we are currently making use of a list containing string elements.
There are a couple of ways to fix this.
Either change the variable called filename to the type set.
In the variables lecture,
we learned that a set is similar to a list,
but it cannot contain duplicate elements.
Once we change the variable type and then run Terraform plan,
we should see that there are three files to be created.
Another way to fix this error
while retaining the variable type as a list
is to make use of another built-in function.
This time, we'll make use of the toset function,
which will convert the variables from a list to a set.
Once this is done,
Terraform plan command should now work as expected.
Now let us replicate the same scenario
as the one we did earlier with the count meta argument
and delete the first element with the value/slash/root pets.txt from the list.
When we run Terraform plan now,
we can see that only one resource is said to be destroyed,
the file with the name pets.txt.
The other resources will be untouched.
To see how this is working,
let us create an output variable called pets
to print the resource details like we did with the example using count.
From the Terraform output command,
we can now see that the resources are stored as a map and not a list.
When we use for_each instead of count,
the resources are created as a map and not a list.
This means that the resources are no longer identified by the index,
thereby bypassing the issues that we saw when we use count.
They are now identified by the keys
which are file names/root/..txt
and /root/cat.txt,
which are used by the for_each argument in the configuration file.
If we compare this to the earlier output
that we got when we use count,
we can see the difference in how the resources are created.
The count option created it as a list and the for_each created it as a map.
There are a few other meta arguments in Terraform
such as provisioners, providers, backends, et cetera.
We will see that later in this course.
Now let's head over to the hands-on labs
and practice working with the for_each meta argument in Terraform.