In the previous article we have already learn to iterate with count structure and also we have how it works and its disadvantages, In this article we will look deeply into for_each, which is another way to achieve looping in terraform.
The simplest example I can think of is to create some 10 or 20 databases in SQL server. Using for_each in these scenarios will make you code more compact and concise. you can make it more complex using the object data type which we will see in the end. Let’s see the basic use by creating 10 files locally with the names given in a list variable.
From the example, we can see that we have to create 3 files without repeating the code. This we can achieve using for_each. so first we have to write for_each argument in the resource which should be looped. We have to change the type to set using the toset function since for_each only accepts unique values. once we have used for_each in resource block, it will enable us to use object called each and each has an attribute called value which is the pointer to the data points mentioned against the for_each, In our example we have given file names so each.value will be pointing to the values “file1”, “file2” and “file3” in respective iterations. The below is the plan for the above code.
Complex for_each example
If we use the object type, we can unleash even better looping with conditionality. Go through this blog to learn about object type and this one to learn about conditional resourcing in terraform.
Let’s take a example like you have few databases and there is a status and the terraform will create the db only if the status is enabled, other wise it won’t. But you need to store that list since the status will be change to and from on time to time. In that case we can create a map of objects
We can create a object that has details about databases just like below.
Now we will iterate through this to create databases only whose status is true. The below way of writing for loop as a value to for_each will help you.
Hope you understand how to iterate over and how to convert your use-case into looping. Please comment you doubts, Happy to help.