Terraform: AWS Target Group unable to add multiple targets

2.4k views Asked by At

I am trying to create ALB and Web Servers by using modules. While Web Servers and ALB gets created, I am unable to add the web servers as targets to the target group. The first one gets attached while the 2nd one fails.

Error: Error registering targets with target group: ValidationError: Instance ID ' i-0cf0a85c8866214ca' is not valid

Below are my code snippets: load_balancer\main.tf

.
.
resource "aws_alb_target_group_attachment" "tg_attach" {
  count = var.tg
  target_group_arn = aws_alb_target_group.front_end_tg.arn
  port = 80
  target_id = element(split(",", var.web_server_id), count.index)
}

web-servers\output.tf

output "web_server_id" {
  value = join(", ", aws_instance.web.*.id)
}

root\main.tf

#Deploy Application Load Balancer
module "load_balancer" {
  source         = "./load_balancer"
  alb_depends_on = [module.web_servers]
  pubsubnets     = module.networking.public_subnets
  alb_source     = module.networking.alb_source
  alb_perf       = module.networking.alb_perf
  web_server_id  = module.web_servers.web_server_id
  perf_vpc       = module.networking.vpc_id
  tg             = var.web_count
}

root\terraform.tfvars

web_count     = 2

Could anyone please advise how do I make the error go away? The question is probably similar to Not able to add multiple target_id inside targer group using terraform. I tried the solutions presented there, but was unable to resolve the issue.

Terraform v0.12.29

AWS Console enter image description here enter image description here

1

There are 1 answers

1
rkm On BEST ANSWER

I think the problem is the leading space in instance name. When you define the output, you join by the comma + space:

output "web_server_id" {
  value = join(", ", aws_instance.web.*.id)
}

However, when you split it, you only use comma:

target_id = element(split(",", var.web_server_id), count.index)

Also in the error message there is a space in the instance name and it seems to be a reason why it fails.