如何将现有的 EIP 分配从变量附加到 NLB

How do I attach an existing EIP allocation to a NLB from a variable

我想为每个子网和每个 NLB 分配一组预定义的 EIP。我有以下变量:

swarm_subnets = [
  "subnet-xxxx",
  "subnet-yyyy"
]
services = {
  "service1" = {
    name = "service1"
    port = "30081"
    eip_allocation = [
        "eipalloc-xxxxxx",
        "eipalloc-xxxxxx"
    ]
  },
  "service2" = {
    name = "service2"
    port = "8445"
    eip_allocation = [
        "eipalloc-xxxxxx",
        "eipalloc-xxxxxx"
    ]
  },
  "service3" = {
    name = "service3"
    port = "8444"
    eip_allocation = [
        "eipalloc-xxxxxx",
        "eipalloc-xxxxxx"
    ]
  }
}

如何在 aws_lb 资源内的动态块中使用 eip_allocation 值?

resource "aws_lb" "this" {
    for_each = var.services

    name               = "nlb-${each.key}-${var.environment}"
    internal           = false
    load_balancer_type = "network"
    dynamic "subnet_mapping" {
        for_each = var.swarm_subnets
        content {
            subnet_id = subnet_mapping.value
            allocation_id = <eip_allocation from the services variable>
        }
    }
    tags = local.common_tags
}

终于想通了。

resource "aws_lb" "this" {
  for_each = var.services

  name               = "nlb-${each.key}-${var.environment}"
  internal           = false
  load_balancer_type = "network"
  dynamic "subnet_mapping" {
    for_each = var.swarm_subnets
    content {
      subnet_id     = subnet_mapping.value
      allocation_id = each.value.eip_allocation[index(var.swarm_subnets, subnet_mapping.value)]
    }
  }
  tags = local.common_tags
}

当它循环遍历 var.swarm_subnets 中的值时,我使用 index() 获取当前子网的索引值(在本例中为 0 和 1)以获取 [=13] 中的值=].