How to iterate in terraform with for_each.

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.

Creating number of files, with their names in a variable using for_each
creating files through looping

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.

The plan for above for_each use-case
Please see the file names and also it creates 3 files.

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.

databases variable for iterating over and creating a number of databases using for_each.
Creating a map of maps which has details of databases.

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.

Using for_each to create databases.
Creates the databases using above data structure.

Hope you understand how to iterate over and how to convert your use-case into looping. Please comment you doubts, Happy to help.

Leave a comment

Your email address will not be published. Required fields are marked *