簡體   English   中英

如何在 terraform 中的“su.net_mapping”中使用“for_each”,這樣我就可以 map 為每個“su.net_id”創建的每個彈性 IP

[英]How to use "for_each" inside the "subnet_mapping" in terraform so I can map the each elastic IPs created to each "subnet_id"

// 這將創建我的 EIP:

resource "aws_eip" "nlb_eips" {
  count = length(module.vpc.public_subnets)
}

// 這需要創建我的 NLB,並附加 EIP:

resource "aws_lb" "data-lake-NLB" {

  name               = "data-lake-NLB"
  internal           = false
  load_balancer_type = "network"
  enable_deletion_protection = true
  subnet_mapping {
    for_each = {for k,v in     => ... )  }     ????? # This part I can't figure out. 
    subnet_id = each.key
    allocation_id = each.value
  }
}

您可以使用動態塊

resource "aws_lb" "data-lake-NLB" {

  name               = "data-lake-NLB"
  internal           = false
  load_balancer_type = "network"
  enable_deletion_protection = true

  dynamic "subnet_mapping" {

      for_each = range(length(var.public_subnets))

      content {
         subnet_id     = module.vpc.public_subnets[ingress.key].id
         allocation_id = aws_eip.nlb_eips[ingress.key].id
      }
  }

}

確切的形式取決於module.vpc.public_subnets實際上是什么。

  resource "aws_lb" "data-lake-NLB" {
  name               = "data-lake-NLB"
  internal           = false
  load_balancer_type = "network"
  enable_deletion_protection = true

  dynamic "subnet_mapping" { 
      for_each = local.for_each_map      
 aws_eip.nlb_eips[*].public_ip)
    content {
      subnet_id = subnet_mapping.key
      allocation_id = subnet_mapping.value
    }
  }
}
locals {
  for_each_map = zipmap(module.vpc.public_subnets, aws_eip.nlb_eips[*].id) 
}

我遇到了幾乎相同的問題(在我的例子中 IP 地址來自一個變量)並且不得不從不同的地方拼湊出一些解決方案。 這對我有用:

variable "ip_addr" {
  description = "List of static IP addresses to assign to the load balancer"
  type = list
}

data "aws_subnets" "public" {
  filter {
    name = "vpc-id"
    values = [data.aws_vpc.main.id]
  }
  tags = {
    Type = "public"
  }
}

data "aws_eip" "lb" {
  count = length(var.ip_addr)
  public_ip = var.ip_addr[count.index]
}

resource "aws_lb" "gateway-lb" {
  name               = "gateway-nlb"
  internal           = false
  load_balancer_type = "network"
  idle_timeout       = 300
  enable_deletion_protection = true

  dynamic "subnet_mapping" {
    for_each = range(length(data.aws_subnets.public.ids))
    content {
      subnet_id = data.aws_subnets.public.ids[subnet_mapping.key]
      allocation_id = data.aws_eip.lb[subnet_mapping.key].id
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM