【问题标题】:How to create multiple target groups for multiple instances in aws using terraform?如何使用 terraform 在 aws 中为多个实例创建多个目标组?
【发布时间】:2021-07-30 12:29:33
【问题描述】:

我有 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
  }
}

现在我必须结合这个服务名称变量(列表)和 net-lb-ports(地图)来创建目标组

我可以在下面做,但只有 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)

请指导我

【问题讨论】:

  • 所有 3 个服务的端口完全相同?
  • @Marcin 是的,所有 3 个服务都是相同的端口
  • 如果所有 3 个服务都有相同的端口,为什么不直接对它们进行硬编码,或者直接从变量分配?如果端口始终相同,则不需要任何循环。
  • @marcin 将来可能会改变,所以我不想硬编码它们

标签: terraform terraform-provider-aws


【解决方案1】:

我如下更改了变量并能够创建目标组

   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"
   } 
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2021-08-09
    • 2019-02-27
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多