Is there a way of converting the value of the below local (local.nlb_config) to use in a for_each?
nlb_config= [
{
"ec2_id" = "i-yyyyyyyyyyyyyy"
"nlb_target_name" = "example-nlb1"
"nlb_target_port" = "3689"
"nlb_target_protocol" = "TCP"
"nlb_target_type" = "instance"
},
{
"ec2_id" = "i-xxxxxxxxxx"
"nlb_target_name" = "example-nlb1"
"nlb_target_port" = "3689"
"nlb_target_protocol" = "TCP"
"nlb_target_type" = "instance"
},
{
"ec2_id" = "i-yyyyyyyyyyyyyy"
"nlb_target_name" = "example-nlb2"
"nlb_target_port" = "53"
"nlb_target_protocol" = "TCP"
"nlb_target_type" = "instance"
},
{
"ec2_id" = "i-xxxxxxxxxx"
"nlb_target_name" = "example-nlb2"
"nlb_target_port" = "53"
"nlb_target_protocol" = "TCP"
"nlb_target_type" = "instance"
},
]
I have constructed that local but now need it in the correct format to use in a for_each. The local was created like below:
variable "target_id" {
type = map(object({
id = string
availability_zone = string
tags = map(string)
}))
}
variable "nlb_target_group" {
type = map(object({
nlb_target_name = string
nlb_target_port = string
nlb_target_protocol = string
nlb_target_type = string
#health_check = map(string)
}))
}
nlb_target_group = {
group1 = {
nlb_target_name = "example-nlb1"
nlb_target_port = "3689"
nlb_target_protocol = "TCP"
nlb_target_type = "instance"
},
group2 = {
nlb_target_name = "example-nlb2"
nlb_target_port = "53"
nlb_target_protocol = "TCP"
nlb_target_type = "instance"
}
}
locals {
ec2sflat = [
for key, ec2 in var.target_id : {
ec2_id = ec2.id
}
]
nlbsflat = [
for key, nlb in var.nlb_target_group : {
key = key
nlb_target_name = nlb.nlb_target_name
nlb_target_port = nlb.nlb_target_port
nlb_target_protocol = nlb.nlb_target_protocol
nlb_target_type = nlb.nlb_target_type
}
]
nlb_config = [
for pair in setproduct(local.nlbsflat, local.ec2sflat) : merge(pair[0], pair[1])
]
}
I then want to use local.nlb_config in a for_each like below
resource "aws_lb" "this" {
name = var.nlb_name
internal = var.internal
load_balancer_type = "network"
subnets = var.nlb_subnets
enable_deletion_protection = var.enable_deletion_protection
enable_cross_zone_load_balancing = var.enable_cross_zone_load_balancing
}
resource "aws_lb_target_group" "this" {
for_each = local.nlb_config
name = each.value.nlb_target_name
port = each.value.nlb_target_port
protocol = each.value.nlb_target_protocol
target_type = each.value.nlb_target_type
vpc_id = var.vpc_id
}
resource "aws_lb_target_group_attachment" "this" {
for_each = local.nlb_config
target_group_arn = aws_lb_target_group.this[each.key].arn
target_id = each.value.ec2_id
port = var.target_group_attachment_port
}
resource "aws_lb_listener" "this" {
for_each = local.nlb_config
load_balancer_arn = aws_lb.this.arn
port = var.nlb_listner_port
protocol = var.nlb_listner_protocol
default_action {
type = var.nlb_listner_default_action_type
target_group_arn = aws_lb_target_group.this[each.key].arn
}
}
I seem so close so hopefully an easy solution. Thanks