如何使用 terraform 在 aws 中为多个实例创建多个目标组?

时间:2021-05-08 12:55:31

标签: terraform terraform-provider-aws

我有 3 个名为 valid、jsc、test 的服务,每个服务在 3 个区域中有 3 个实例。现在我必须为每个服务创建一个目标组并将实例附加到相同的组。现在我不知道如何组合端口 80,443 和服务名称以创建目标组

variable "service-names" {
  type = list
  default = ["valid","jsc","test"]
  
}

variable "net-lb-ports" {
  type    = map(number)
  default = {
  TCP = 80
  TCP = 443
  }
}

现在我必须结合这个 service-names 变量(list)和 net-lb-ports(map)来创建目标组

我能够在下面做,但只有 1 个端口,而且还通过对值进行了编码

resource "aws_lb_target_group" "ecom-nlb-tgp" {
   for_each = toset(var.service-names)
   name = "${each.value}-nlbtgp"
   port = 80
   protocol = "TCP"
   vpc_id = aws_vpc.ecom-vpc.id
   target_type = "instance"
   deregistration_delay    = 90
   health_check {
     interval            = 30
     port                = 80
    protocol            = "TCP"
     healthy_threshold   = 3
     unhealthy_threshold = 3
   }
   tags = {
     "Name" = "${each.value}-nlb-tgp"
   }

所以我总共需要 6 个目标组,其中 3(服务名称)* 2 个端口(80,443)

请指导我

1 个答案:

答案 0 :(得分:0)

我像下面那样更改了变量并能够创建目标组

   variable net-lb-ports {
      type = map
      default = { 
    port1 = {
    port = 80
    protocol = "TCP"
    }
    port2 = {
    port = 443
    protocol = "TCP"
    }
      }
    }

    locals {
      merged_lbport_svc = flatten([
        for s in var.service-names :  [
          for v in var.net-lb-ports : {
            service = s
            port = v.port
            protocol = v.protocol
          }
        ]
      ])
    }

resource "aws_lb_target_group" "ecom-nlb-tgp" {
  for_each = {for idx,svc in local.merged_lbport_svc : "${svc.service}-${svc.port}-${svc.protocol}" => svc}
  #for_each = {for idx,svc in local.merged_lbport_svc : idx => svc}
  name = "ecom-${each.value.service}-${each.value.port}-${each.value.protocol}-nlbtgp"
  port = each.value.port
  protocol = each.value.protocol
  vpc_id = aws_vpc.ecom-vpc.id
  target_type = "instance"
  deregistration_delay    = 90
  health_check {
    interval            = 30
    port                = each.value.port
    protocol            = each.value.protocol
    healthy_threshold   = 3
    unhealthy_threshold   = 3
    }
   tags = {
     "Name" = "ecom-${each.value.service}-${each.value.port}-${each.value.protocol}-nlbtgp"
   } 
 }