Terraform 迭代字典列表

Terraform iterate over list of dicts

有一个字典列表,其中一个键包含另一个列表。我想创建一个我可以在 for_each 中使用的对象,它将重复 key1、key2、list_key 的次数与列表项的数量一样多。

迭代它的最佳方法是什么?

my_list = [
   {
    "key1"     = "value1"
    "key2"     = "value2"
    "list_key" = ["l_value1", "l_value2"]
   },
   {
    "key1"     = "value3"
    "key2"     = "value4"
    "list_key" = ["l_value3"]
   }
]

我尝试使用这种方法在本地人中将其展平,但是当我在 for_each 中使用它时,它显示 for_each supports maps and sets of strings, but you have provided a set containing type object

locals {
    params = flatten([
       for element in var.my_list:
         [
          for k in element["list_key"]:
           {
             "key1"     = element["key1"]
             "key2"     = element["key2"]
             "list_key" = k
           }
         ]
       ]
     )
   }

然后我想在我的资源中使用它:

resource "an_aws_service" "my_service" {
    for_each       = toset(local.params)
    name           = each.value.key1
    something      = each.value.key2
    something_else = each.value.list_key
}

如果输出看起来像这样,我可能会用 toset 处理它,但也许还有其他方法可以展平它:

[{
    "key1"     = "value1"
    "key2"     = "value2"
    "list_key" = "l_value1"
},
{
    "key1"     = "value1"
    "key2"     = "value2"
    "list_key" = "l_value2"
},
{
    "key1"     = "value3"
    "key2"     = "value4"
    "list_key" = "l_value3"
}]

你的代码扁平化

locals {
  params = flatten([
    for element in var.my_list :
    [
      for k in element["list_key"] :
      {
        "key1"     = element["key1"]
        "key2"     = element["key2"]
        "list_key" = k
      }
    ]
    ]
  )
}

...生成对象列表(如错误消息所述,也如您在问题中指出的那样):

name = [
  {
    "key1" = "value1"
    "key2" = "value2"
    "list_key" = "l_value1"
  },
  {
    "key1" = "value1"
    "key2" = "value2"
    "list_key" = "l_value2"
  },
  {
    "key1" = "value3"
    "key2" = "value4"
    "list_key" = "l_value3"
  },
]

如果你想用这个数组来创建多个资源,你要么把这个数组转换成map:

resource "an_aws_service" "my_service" {
    for_each       = { for index, value in local.params : index => value }
    name           = each.value.key1
    something      = each.value.key2
    something_else = each.value.list_key
}

或使用count代替for_each

resource "an_aws_service" "my_service" {
    count          = length(local.params)
    name           = local.params[count.index].key1
    something      = local.params[count.index].key2
    something_else = local.params[count.index].list_key
}

您不能在 for_each 中使用对象列表。您要么必须有一个 map(第一个示例),要么使用 count 而不是 for_each