AWS target group attachment target_id error

Hi team, can anyone help me to understand what i am doing wrong when placing the ec2 instance ids as a target id?

resource "aws_lb_target_group_attachment" "target-group-for-mqtt" {
  target_group_arn = aws_lb_target_group.target-group-for-mqtt.arn
  target_id        = [aws_instance.ec2-mqtt-1a.id, aws_instance.ec2-mqtt-2c.id]
  port             = 1883
}

errors is the following, thanks!

 tf plan
╷
│ Error: Incorrect attribute value type
│ 
│   on servers.tf line 165, in resource "aws_lb_target_group_attachment" "target-group-for-mqtt":
│  165:   target_id        = [aws_instance.ec2-mqtt-1a.id, aws_instance.ec2-mqtt-2c.id]
│     ├────────────────
│     │ aws_instance.ec2-mqtt-1a.id will be known only after apply
│     │ aws_instance.ec2-mqtt-2c.id will be known only after apply
│ 
│ Inappropriate value for attribute "target_id": string required.

As per Terraform docs, target id is a string not a list of strings.
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lb_target_group_attachment

You might be able to achieve what you are expecting with below

resource "aws_lb_target_group_attachment" "target-group-for-mqtt" {
  for_each = toset([aws_instance.ec2-mqtt-1a.id, aws_instance.ec2-mqtt-2c.id])
  target_group_arn = aws_lb_target_group.target-group-for-mqtt.arn
  target_id        = each.key
  port             = 1883
}
1 Like

Thank you for your response!