循环遍历地图并跳过空项目

One*_*neK 2 terraform terraform-provider-aws

我想要的是

在 terraform 中,我有一张地图service_map

variable "service_map" {
  type        = map
  description = "Map of some services and their ports."
  default     = {
    "dns"    = "53"
    "web"    = "443"
    "ssh"    = "22"
    "proxy"  = ""
  }
}
Run Code Online (Sandbox Code Playgroud)

要在 AWS 上创建 LB 侦听器,我想调用资源aws_lb_listener,循环遍历地图service_map跳过所有没有值的项目(在本例中,仅跳过proxy):

resource "aws_lb_listener" "listeners" {
  for_each          = var.service_map
  load_balancer_arn = aws_lb.all_lbs[each.key].arn
  port              = each.value
  protocol          = each.key != "dns" ? "TCP" : "TCP_UDP"
  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.service_map-tg[each.key].arn
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的

  1. 创建第二个本地映射,其中包含所有键=值对,其中值不为空:
locals {
  service_map_temp = [ for service, port in var.service_map : service, port if port != "" ]
}
Run Code Online (Sandbox Code Playgroud)

哪个不起作用:Extra characters after the end of the 'for' expression.. 我想还有比这种方法更聪明的解决方案。

  1. 想法:跳过空each.values:
resource "aws_lb_listener" "listeners" {
  for_each          = var.service_map
  load_balancer_arn = aws_lb.all_lbs[each.key].arn
  port              = each.value != "" # Skipping part
  protocol          = each.key != "dns" ? "TCP" : "TCP_UDP"
  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.service_map-tg[each.key].arn
  }
}
Run Code Online (Sandbox Code Playgroud)

但我怀疑这是否会起作用,因为我仍在调用资源,但端口为空,这会失败。由于我刚刚开始使用 terraform,我确信有一个我还没有想到/读过的解决方案。

Mar*_*ins 10

您的第一个解决方案失败了,因为您使用了列表括号[ ... ],但您打算生成地图。生成地图for,请使用映射括号{ ... }

locals {
  service_map_temp = {
    for service, port in var.service_map :
    service => port if port != ""
  }
}
Run Code Online (Sandbox Code Playgroud)

主要区别在于,映射for表达式在冒号后需要两个表达式(键和值),而列表for表达式只需要一个。

如果您愿意,可以直接将该表达式内联到参数中for_each,以将所有内容都放在一个块中:

resource "aws_lb_listener" "listeners" {
  for_each = {
    for service, port in var.service_map :
    service => port if port != ""
  }

  load_balancer_arn = aws_lb.all_lbs[each.key].arn
  port              = each.value
  protocol          = each.key != "dns" ? "TCP" : "TCP_UDP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.service_map-tg[each.key].arn
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 语法不太正确,必须是 `=>` 才能创建映射: `for_each = { for service, port in var.service_map : service => port if port != "" }` (2认同)