Reputation: 928
I have 3 services named valid,test,jsc and each have 3 ec2 instances and each have 1 loadbalancer target group.Now i want to attach each 3 respective ec2 instances to their target group
variable "service-names" {
type = list
default = ["valid","jsc","test"]
}
locals {
helper_map = {for idx, val in setproduct(var.service-names, range(var.instance_count)):
idx => {service_name = val[0]}
}
}
resource "aws_lb_target_group" "ecom-tgp" {
for_each = toset(var.service-names)
name = "${each.value}-tgp"
port = 80
protocol = "TCP"
vpc_id = aws_vpc.ecom-vpc.id
target_type = "instance"
deregistration_delay = 90
health_check {
interval = 30
port = 80
protocol = "TCP"
healthy_threshold = 3
unhealthy_threshold = 3
}
tags = {
"Name" = "${each.value}-tgp"
}
}
output "ecom-instance-details" {
value = data.aws_instances.ecom-instances
}
Below is the sample i service instances details from terraform output
ecom-instance-details = {
"test" = {
"filter" = toset(null) /* of object */
"id" = "ap-south-1"
"ids" = tolist([
"i-0fab28125d684f9d2",
"i-0b90e3501715681df",
"i-066bff51352660006",
])
"instance_state_names" = toset([
"running",
"stopped",
])
"instance_tags" = tomap({
"Name" = "test-service"
})
"private_ips" = tolist([
"10.0.3.11",
"10.0.3.10",
"10.0.3.8",
])
"public_ips" = tolist([])
}
vpc-id = "vpc-051198b7ebaa3bd53"
I'm trying like below.But since it is having 3 ids in a list,it is not accepting that to pass to target_id which is basically a string
resource "aws_lb_target_group_attachment" "ecom-tga" {
for_each = local.helper_map
target_group_arn = aws_lb_target_group.ecom-tgp[each.value.service_name].arn
port = 80
target_id = data.aws_instances.ecom-instances[each.value.service_name].ids
}
Could you please guide me
Upvotes: 1
Views: 819
Reputation: 238329
If I understand correctly, you can construct a helper local variable and use that:
locals {
env_instance_map = merge([for env, value in var.ecom-instance-details:
{
for id in value.ids:
"${env}-${id}" => {
"env" = env
"id" = id
}
}
]...)
}
resource "aws_lb_target_group_attachment" "ecom-tga" {
for_each = local.env_instance_map
target_group_arn = aws_lb_target_group.ecom-tgp[each.value.env].arn
port = 80
target_id = each.value.id
}
Upvotes: 2