Is there any way to select specific value from for_each in another resource section?
With the following I am able to create multiple target_groups without any issues.
resource "aws_lb_target_group" "target_group" {
for_each = var.target_group
name = format("%s%s-%s","TG-",var.name, each.value.incoming_port)
port = each.value.incoming_port
protocol = each.value.incoming_protocol
proxy_protocol_v2 = false
vpc_id = data.aws_vpc.vpc.id
target_type = "instance"
}
Here my requirement is to create only one listener with forwarding. So I want to select 1 target group arn (Can be the first one or any other) to create below listener resource. Using for_each I can start a loop with all the target_group but that is not the requirement. Tried many times with different approach but no success yet.
resource "aws_lb_listener" "forward_443" {
#for_each = aws_lb_target_group.target_group
default_action {
target_group_arn = aws_lb_target_group.target_group[each.value].id == "TG-EX-DEV-7776" ? aws_lb_target_group.target_group[each.value].arn : ""
#target_group_arn = each.value.port == 7776 ? each.value.arn : ""
#target_group_arn = element(aws_lb_target_group.target_group[each.key].arn, count.index)
#target_group_arn = local.value
type = "forward"
}
load_balancer_arn = aws_lb.lb.arn
port = 443
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-FS-1-2-Res-2020-10"
certificate_arn = aws_acm_certificate.cert.arn
}
in simple, i wanted to create 3 target_group and attach one forward rule to one of them only. terraform should not look for other target_group's
CodePudding user response:
If you just want to get a single value from your aws_lb_target_group.target_group
, you can use values:
resource "aws_lb_listener" "forward_443" {
default_action {
target_group_arn = values(aws_lb_target_group.target_group)[0].id
type = "forward"
}
load_balancer_arn = aws_lb.lb.arn
port = 443
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-FS-1-2-Res-2020-10"
certificate_arn = aws_acm_certificate.cert.arn
}