Terraform HCL - 将列表转换为对象地图? [英] Terraform HCL - Convert List to Map of Objects?

查看:13
本文介绍了Terraform HCL - 将列表转换为对象地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串列表,我需要将其转换为地图,以便稍后在其上执行 jsonencode 时,它不会创建数组.这是因为在 json-schema 中 properties: { ... } 不是一个属性列表,而是一个映射.

I have a list of strings, that I need to transform to a map so that when I do jsonencode on it later, it doesn't create an Array. This is because in json-schema the properties: { ... } is not a list of properties but actually a map.

所以我列表中的每个属性都应该以键值映射的形式出现.其中键是属性名称,值是另一个映射或对象{type";=字符串"}.

So each property in my list should come out as a key - value map. Where the key is the property name and the value is another map or object { "type" = "string" }.

additional-properties = [
  for prop in local.prop-list:
    { prop = { "type" = "string" }}
]

我的第一次尝试以地图对象列表结束,而不是属性地图.

My first attempt ends up as a list of map objects, instead of a map of properties.

有没有更好的方法来实现这一点?

Any better way to accomplish this?

我的最终目标是能够在 API 网关模型的 json 模式中对此使用 jsonencode -

My ultimate goal is to be able to use jsonencode on this in a json schema for an API Gateway model -

"properties": {
  "prop1": {
    "type": "string"
  },
  "prop2": {
    "type": "string"
  }
}

推荐答案

当你指定赋值给additional-properties为:

[
  for prop in local.prop-list:
    { prop = { "type" = "string" }}
]

我们可以删除 lambda 和变量以查看构造函数的结果类型将是:

we can remove the lambda and variables to see the resulting type from the constructors will be:

[{{}}]

这是一个嵌套在 List 中的 Map.

which is a nested Map inside a List.

由于您想要一个具有 { prop { type = string } } 结构的嵌套 Map,我们需要相应地指定构造函数:

Since you want a nested Map with a { prop { type = string } } structure, we need to specify the constructors accordingly:

additional-properties = { # outside map with "prop" key and map value
  for prop in local.prop-list:
    prop => { "type" = "string" } # nested map with "type" key and "string" value
}

还要注意从 ==> 的更改,以获得正确的 lambda 迭代器映射键值对分配语法.

Note also the change from = to => for proper lambda iterator map key-value pair assignment syntax.

这篇关于Terraform HCL - 将列表转换为对象地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆