How to iterate over terraform resources with count

Imagine you have to create a 100 files on you remote server or let’s say you need to create 30 virtual machines as part of your infrastructure setup. If you want to accomplish this task via terraform, you should learn COUNT and this is a must read blog for you.

Terraform created a design pattern for you to overcome this hectic task, which is count. Inside any resource block, you can have an argument “count” and assign the number which tells how many you want. Below example shows how to use

how to use count assignment
count is not an argument specific to any provider.

Even though direct assignment of number helps, However it leaves the iteration over data out of scope. To achieve the exact same thing terraform added index attribute to the count.

Count with data

Let’s say you have a list of databases to create. You can learn more about the list data type here. As you are aware of it, the index of list starts with 0. Below example shows you exact same thing.

count = 3 means in
iteration = 1 --> count.index value is 0
iteration = 2 --> count.index value is 1
iteration = 3 --> count.index value is 2

For suppose you have that list of db names, you can assign the length of the list to count which make sure number of resources gets created equal to the number of dbs in the list. Now let’s say you have a name argument and it needs the exact data element of the list. For this exact case you can use index attribute whose value increase over iterations and you can access by count.index as the index to list eg: var.list_data[count.index].

The below example shows how to create a list of files by its name.

count with files
creating 3 files with count
plan showing how count works
see the plan for the above code. observe the index and file names as highlighted.

Even though it looks fine for the second case, but it is not. Let’s say you want to delete the first file and so you removed first element from the list, which unnecessarily recreates the first two files. Since the element at index 0 and index 1 got changed. The below examples shows what I’m saying.

code with element removed while using count.
code after removing first file.
count behaviour after removing one file from list
plan that shows first two replacements and third one deletion.

Ironically, It deletes the third file rather than first file. However this can be done without this unnecessary deletion and creation using for_each. Which is the topic for next blog. Please stay tuned. happy infra.

3 comments

Leave a comment

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