0

是否有可能在不诉诸于的情况下HCL让嵌套迭代返回一个平面?list(map)flatten

我有这个:

locals {
  mappings = flatten([
    for record_type in var.record_types : [
      for host in var.hosts : {
        type = record_type,
        host = host
      }
    ]
  ])
}

我想消除对flatten这样的需求:

locals {
  mappings = [
    for record_type in var.record_types :
      for host in var.hosts : {
        type = record_type,
        host = host
      }
    ]
}

但似乎每个人都for .. in必须返回数据。

4

1 回答 1

1

我能想到的一种只有一个 for 循环的替代方法是使用setproduct()

variable "record_types" {
  default = ["type1", "type2"]
}

variable "hosts" {
  default = ["host1", "host2"]
}

locals {
  mappings = [
    for i in setproduct(var.record_types, var.hosts) : {
      type = i[0],
      host = i[1],
    }
  ]
}

output "mappings" {
  value = local.mappings
}

terraform apply 后导致:

Outputs:

mappings = [
  {
    "host" = "host1"
    "type" = "type1"
  },
  {
    "host" = "host2"
    "type" = "type1"
  },
  {
    "host" = "host1"
    "type" = "type2"
  },
  {
    "host" = "host2"
    "type" = "type2"
  },
]

当然,这里的两个变量需要是独立的集合。

如果您想支持重复项或具有相关输入,flatten()则可以使用两个循环。

于 2020-11-10T05:17:22.773 回答