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:
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.
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:
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.
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.
With the below code, terraform will create 5 IAM users. But the problem is that all will have the same name:
Count.index allows to fetch the index of each iteration in the loop:
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:
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 😃💙.