'terraform for loop list for target_groups with a combine variable

Is there a way to use the below list in a for loop and add in the target_groups ? I am trying to use the prefix with target_groups variable in a for-loop. I have tested also for_each. The target_groups expects the list format but the for_each does not give that expected result.

variable "prefix" {
  description = "NLB Prefix"
  type        = any
  default = "test-target"
}

variable "target_groups" {
  description = "NLB"
  type        = any
  default = {
    tg1 = {
      name_prefix          = "test"
      backend_protocol     = "TCP"
      backend_port         = 443
      target_type          = "ip"
      deregistration_delay = 10
      preserve_client_ip   = true
      stickiness = {
        enabled = true
        type    = "source_ip"
      }
      targets = {
        appl1 = {
          target_id = "191.11.11.11"
          port      = 443
        }
      }
    },
    }
  }
}

I tried the list below for_each

module "g-appl_nlb" {
  source = "../../modules/compute/lb"

  name               = format("%s-g-appl-nlb", var.name_prefix)
  load_balancer_type = "network"
  vpc_id             = data.aws_vpc.target_vpc.id
  ...

  target_groups = [

    for_each = var.target_groups 
      name_previs          = var.prefix
      backend_protocol     = each.value["backend_protocol"]
      backend_port         = each.value["backend_port"]
      target_type          = each.value["target_type"]
      deregistration_delay = each.value["deregistration_delay"]
      preserve_client_ip   = each.value["preserve_client_ip"]
      stickiness           = each.value["stickiness"]
  ]
....



Solution 1:[1]

Basically, I managed the solved my request with the below approach.

locals {
  target_groups = flatten([

      for tg_data in var.target_groups: {
        name_prefix          = "var.name_prefix"
        backend_protocol     = tg_data.backend_protocol
        backend_port         = tg_data.backend_port
        target_type          = tg_data.target_type
        deregistration_delay = tg_data.deregistration_delay
        preserve_client_ip   = tg_data.preserve_client_ip
        ....
  ])
}
module "g-appl_nlb" {
  source = "../../modules/compute/lb"

  name               = format("%s-g-appl-nlb", var.name_prefix)
  load_balancer_type = "network"
  vpc_id             = data.aws_vpc.target_vpc.id
  ...

  target_groups = local.target_groups

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kenot Solutions