How to create a single map of object to use in for_each, using one tuple and two list of strings
Let’s say I have a tuple/list of instance IDs or instance IPs coming from an ec2 module and a tuple/list of target group arns from ALB module as shown below.
instance_ids =["10.1.1.1", "10.2.2.2"]
target_gropup_arn = ["arn1", "arn2"]
In main.tf
output "out" {
value = local.aws_lb_target_group_attachment
}
variable "target_groups" {
type = any
default = [
{
protocol = "TCP"
port = "22"
},
{
protocol = "TCP"
port = "443"
}
]
}
locals {
instance_ids = toset(["10.1.1.1", "10.2.2.2"])
target_gropup_arn = toset(["arn1", "arn2"])
aws_lb_target_group_attachment = { for idx in flatten([for instance_ids in local.instance_ids :
[for tg in var.target_groups :
[for arn in local.target_gropup_arn :
{
target_id = instance_ids
target_group_arn = arn
port = tg.port
}]
]]) : "${idx.target_id}:${idx.port}:${idx.target_group_arn}" => idx }
}
When I run terraform apply I get the below output, but this is not the expected map I need.
Outputs:
out = {
"10.1.1.1:22:arn1" = {
"port" = "22"
"target_group_arn" = "arn1"
"target_id" = "10.1.1.1"
}
"10.1.1.1:22:arn2" = {
"port" = "22"
"target_group_arn" = "arn2"
"target_id" = "10.1.1.1"
}
"10.1.1.1:443:arn1" = {
"port" = "443"
"target_group_arn" = "arn1"
"target_id" = "10.1.1.1"
}
"10.1.1.1:443:arn2" = {
"port" = "443"
"target_group_arn" = "arn2"
"target_id" = "10.1.1.1"
}
"10.2.2.2:22:arn1" = {
"port" = "22"
"target_group_arn" = "arn1"
"target_id" = "10.2.2.2"
}
"10.2.2.2:22:arn2" = {
"port" = "22"
"target_group_arn" = "arn2"
"target_id" = "10.2.2.2"
}
"10.2.2.2:443:arn1" = {
"port" = "443"
"target_group_arn" = "arn1"
"target_id" = "10.2.2.2"
}
"10.2.2.2:443:arn2" = {
"port" = "443"
"target_group_arn" = "arn2"
"target_id" = "10.2.2.2"
}
}
The expected output is (pseudo output)
out = {
"10.1.1.1:22" = {
"port" = "22"
"target_id" = "10.1.1.1"
"target_group_arn" = "arn1"
}
"10.1.1.1:443" = {
"port" = "443"
"target_id" = "10.1.1.1"
"target_group_arn" = "arn1"
}
"10.2.2.2:22" = {
"port" = "22"
"target_id" = "10.2.2.2"
"target_group_arn" = "arn2"
}
"10.2.2.2:443" = {
"port" = "443"
"target_id" = "10.2.2.2"
"target_group_arn" = "arn2"
}
}
This is required so that later I can use it to attach multiple instances using “aws_lb_target_group_attachment” resource.