Search code examples
terraformhcl

Terraform HCL - Convert List to Map of Objects?


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.

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?

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"
  }
}

Solution

  • When you specify the assignment to additional-properties as:

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

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

    [{{}}]
    

    which is a nested Map inside a List.

    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
    }
    

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