This question already has an answer here:
I want to use the count.index in the terraform module for my aws ec2 instance to name the instance in increment order
file: ec2/main.tf
resource "aws_instance" "instance"{
ami = "ami-xxx"
tags {
Name = "var.instance"
}
count = "var.count"
}
file: ec2instance.tf
module "ec2"{
source = "./ec2"
count = 3
instance_name = "firsttypeinstance-${count.index+1}"
}
module "ec20"{
source = "./ec2"
count = 2
instance_name = "secondtype-${count.index+1}"
}
I want the instance name to be populated as
firsttypeinstance-1 firsttypeinstance-2 firsttypeinstance-3
secondtype-1 secondtype-2
but i get the error that i cannot use count index in the module
From terraform doc:
however, you could create the
my_count
variable in your module and use it on resources inside your modulemodule ec2
module main
If you are using terraform 0.12, you are able to use the for loop feature: https://www.terraform.io/docs/configuration/expressions.html#for-expressions
If you are under 0.12(as I do) -- no luck.
Still, adding id to your instances tend to make your infrastructure less "immutable", in my opinion.