DEV Community

Cover image for Terraform Associate Certification: Count & Count index
Daniel Huerta
Daniel Huerta

Posted on

Terraform Associate Certification: Count & Count index

Let's assume, you need to create two EC2 instances in AWS. One of the common approaches is to define two separate resource blocks for aws_instance such as follows:

Screen Shot 2021-08-23 at 15.14.30

Two EC2 instances is not a real problem, but what if we need to create more than that, maybe 10 instances?! 😖 It doesn't seem to be really cool right?

Well, in Terraform there is something named Count Parameter and it can simplify configurations and let you scale resources by simply incrementing a number.

Count parameter

With it, we can simply specify the count value and the resource can be scaled accordingly, for example, let's create 3 EC2 instances with this parameter:

Screen Shot 2021-08-23 at 15.19.08

The instances will be ordered as a list, we will be able to access to them using the position of it, for example instance-1[0].

Count index

In resource blocks where count is set, an additional count object is available in expressions, so you can modify the configuration of each instance.

This object has one attribute:

  • Count index: the distinct index number (starting with 0) corresponding to this instance.

For example:
With the below code, terraform will create 5 IAM users. But the problem is that all will have the same name:

Screen Shot 2021-08-23 at 15.22.14

Count.index allows to fetch the index of each iteration in the loop:

Screen Shot 2021-08-23 at 15.22.48

Closure

Now that you know how to scale resources using this parameter, you can combine it with other TF things such as variables.

We can take advantage of the count.index to use it in a different way:

Screen Shot 2021-08-23 at 15.23.18

In this example we are setting the name of each IAM user according to the position of the variable named elb_names.

Any comments are welcome, remember we are here to help each other 😃💙.

Discussion (0)