Multiple iteration in one resource

In this setup, is it possible to attach all 12 instance all together in aws_lb_target_group_attachment. I tried count, but it is throwing error saying we cannot use both. Then I tried target_id = [for ids in aws_instance.instance : ids], here also error as it is tuple and string is expected. Even tried to convert each value to string. Is there any way to do it.

  count = length(data.aws_ami_ids.api_mainapp_ami.*.ids)
  ami =  element(data.aws_ami_ids.api_mainapp_ami.*.ids[count.index], 12)
  instance_type           = "t3.xlarge"
  associate_public_ip_address = true
  vpc_security_group_ids         = [var.secgroup]
  subnet_id               = "${element(var.vpc_subnets_priv_id, count.index)}"
  tags = {
    Name = "${var.component}-${count.index+1}"
  }

}

LB.....




variable "port_forwarding_config" {
  default = {
      8900        =   "TCP"
      7879       =   "TCP" 
      80         =  "TCP"
      9690        = "TCP"
  }
}




resource "aws_lb_target_group_attachment" "tg-attachment" {
  for_each = var.port_forwarding_config
    target_group_arn  = "${aws_lb_target_group.tg[each.key].arn}"
    port              = each.key
    target_id           = "${aws_instance.instance[1].id}"
}```

The trick is to somehow make yourself a map that you can use with for_each, that does the right thing, which means you need:

  • Map keys, at the top level of the map, which are distinct and give a consistent name to each resource you want to create
  • Map values, which provide you with all of the varying information you need to fill in the resource attributes

For example, and using range(12) to model the instances so I don’t have to set up the AWS provider locally:

merge([
    for port, proto in var.port_forwarding_config :
    {
      for instance in range(12) : "${port}_${proto}_${instance}" => {
        port     = port
        proto    = proto
        instance = instance
      }
    }
  ]...)

(You might replace range(12) with aws_instance.instance[*].id for example.)