问题
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
回答1:
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.
回答2:
From terraform doc:
In addition to the above, the argument names
count
,for_each
andlifecycle
are not currently used by Terraform but are reserved for planned future features.
however, you could create the my_count
variable in your module and use it on resources inside your module
module ec2
resource "aws_instance" "instance"{
ami = "ami-xxx"
tags {
Name = "var.instance-${count.index}"
}
count = "var.my_count"
}
module main
module "ec2"{
source = "./ec2"
my_count = 3
instance_name = "firsttypeinstance" ## actually instance prefix
}
来源:https://stackoverflow.com/questions/56241761/terraform-use-count-index-in-module