I have a variable with a list of load-balancer targets. Ports, healthchecks etc. Defined as follows (with some sane defaults):
variable "port_mappings" {
type = list(object({
containerPort = string
hostPort = string
lbPort = string
host_tls = bool
lb_tls = bool
health_path = string
health_interval = number
unhealthy_threshold = number
health_matcher = string
create_before_destroy = bool
}))
default = [{
containerPort = "8080"
hostPort = "8080"
lbPort = "443"
host_tls = true
lb_tls = true
health_path = "/health"
health_interval = 30
unhealthy_threshold = 5
health_matcher = "200-399"
create_before_destroy = true
}]
}
I then use that list of objects to create a list of resources like so:
resource "aws_lb_target_group" "this" {
for_each = var.port_mappings
name = "${var.environment}-${var.app_name}-http-${each.value.hostPort}"
vpc_id = var.vpc_id
protocol = "TCP"
port = each.value.hostPort
target_type = "ip"
health_check {
port = "traffic-port"
protocol = each.value.host_tls ? "HTTPS" : "HTTP"
path = each.value.health_path
interval = each.value.health_interval
unhealthy_threshold = each.value.unhealthy_threshold
matcher = each.value.health_matcher
}
lifecycle {
create_before_destroy = each.value.create_before_destroy
}
}
Next, I want to create an “aws_lb_listener” resource for each “aws_lb_target_group”, but I need value from both the list of objects (my var) and the list of “aws_lb_target_group” resources.
resource "aws_lb_listener" "this" {
for_each = aws_lb_target_group.this
load_balancer_arn = aws_lb.this.arn
port = **lbPort value from my list of objects var**
protocol = **ternary based on lb_tls bool from my list of objects var**
certificate_arn = aws_acm_certificate.this.arn
default_action {
type = "forward"
target_group_arn = **target group from the list of aws_lb_target_group resources**
}
}
What’s the best way to go about this?