繁体   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