how to get instance id for my module ec2 when i create using for_each and i need instance_id for my module tgroup to assign or join new instance in spesific target group.
my module ec2
resource "aws_instance" "ProductionServer" {
count = length(var.SubnetServer)
ami = module.CreateAMI.AMIId.id
instance_type = var.TypeServer
subnet_id = var.SubnetServer[count.index]
}
ec2/outputs.tf
output "InstanceId" {
value = aws_instance.ProductionServer
description = "get value id"
}
and my module tgroup
resource "aws_alb_target_group_attachment" "TgProdRegister" {
for_each = module.GetInstanceId.InstanceId.id
target_group_arn = var.TgroupArn
target_id = each.value
port = var.TgPort
depends_on = [ module.GetInstanceId ]
}
and GetInstanceId is refferr to module ec2
CodePudding user response:
Since you are using count
for the instances, to return their ids as a list, you would have to do:
output "InstanceId" {
value = aws_instance.ProductionServer[*].id
description = "get value id"
}
Then for the target groups it would be:
resource "aws_alb_target_group_attachment" "TgProdRegister" {
count = length(module.GetInstanceId)
target_group_arn = var.TgroupArn
target_id = module.GetInstanceId.InstanceId[count.index]
port = var.TgPort
}
Buy the way you should consider placing your instances in auto-scaling groups (ASG) if possible.