I have multiple target_groups per NLB and I need to attach multiple instances to each target_group. The target_id
being a string in aws_lb_target_group_attachment
resource, I don't see any easy way to achieve that. This is what I'm doing atm:
variable "nlb_listeners" {
default = [
{
protocol = "TCP"
target_port = "80"
health_port = "1936"
},
{
protocol = "TCP"
target_port = "443"
health_port = "1936"
}
]
}
// Get the instance ids of the NLB members
data "aws_instances" "nlb_insts" {
instance_tags = {
Name = "${var.vpc_names[var.idx]}${var.inst_role}0*"
}
instance_state_names = ["running", "stopped"]
}
// EC2 instances
resource "aws_instance" "insts" {
count = var.inst_count
instance_type = var.inst_type
.......
}
// Creates the target-group
resource "aws_lb_target_group" "nlb_target_groups" {
count = length(var.nlb_listeners)
name = "nlb-tgr-${lookup(var.nlb_listeners[count.index], "target_port")}"
deregistration_delay = var.deregistration_delay
port = lookup(var.nlb_listeners[count.index], "target_port")
protocol = lookup(var.nlb_listeners[count.index], "protocol")
vpc_id = var.vpc_ids[var.idx]
health_check {
port = lookup(var.nlb_listeners[count.index], "health_port")
protocol = lookup(var.nlb_listeners[count.index], "protocol")
interval = var.health_check_interval
unhealthy_threshold = var.unhealthy_threshold
healthy_threshold = var.healthy_threshold
}
}
// Attach the target groups to the instance(s)
resource "aws_lb_target_group_attachment" "tgr_attachment" {
count = length(var.nlb_listeners)
target_group_arn = element(aws_lb_target_group.nlb_target_groups.*.arn, count.index)
target_id = [for sc in range(var.inst_count) : data.aws_instances.nlb_insts.ids[sc]]
port = lookup(var.nlb_listeners[count.index], "target_port")
}
so, I'm getting this error:
Error: Incorrect attribute value type
on ../../modules/elb/balencer.tf line 31, in resource "aws_lb_target_group_attachment" "tgr_attachment": 31: target_id = [for sc in range(2) : data.aws_instances.nlb_insts.ids[sc]]
Inappropriate value for attribute "target_id": string required.
Anyone has any idea how do I achieve that?
Quickly looking at your code I would say this is the mistake that was giving you your error:
data.aws_instances.nlb_insts.ids[sc]
Should be:
data.aws_instances.nlb_insts[sc].ids
The index goes on the resource, then you get the ids from your resource, in your case you were trying to get all the ids of all the resources and then get the index of that, which is not the way to do it!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With