terraformterraform-provider-aws

How to convert list of objects to just objects in terraform


I have the following code in terrraform

resource "aws_cloudwatch_dashboard" "a_dashboard" {
  dashboard_name = "my_dashboard"
  dashboard_body = jsonencode({
    widgets = [
       {
          "height": 6,
          "width": 24,
          "y": 18,
          "x": 0,
          "type": "metric",
          "properties": {
              "metrics": [
          for i, name in "$list_names" :
           [ { "expression": name, "label": i, "id": i },      
             ["abcd", "id":i]
           ]
          ]
          }
        }
     ]
})
}

where list_names is a variable that is a list

list_names=["name0","name1"]

This creates a list of objects for the metrics of the form

"metrics": [ 
     [ { "expression": name0, "label": 0, "id": 0},["abcd","id":0],
      { "expression": name1, "label": 1, "id": 1},["abcd","id":1],
       ...
    ]
   ]

but I would like to get just what is inside the outer list, meaning

  "metrics":[
     { "expression": name0, "label": 0, "id": 0},["abcd","id":0],
     { "expression": name1, "label": 1, "id": 1},["abcd","id":1],
      ...
   ]

I havent figured out how to achieve this in terraform since the for loop needs to create lists/maps. Any ideas?


Solution

  • Use 2 loops and concat like this

    resource "aws_cloudwatch_dashboard" "a_dashboard" {
      dashboard_name = "my_dashboard"
      dashboard_body = jsonencode({
        widgets = [
           {
              "height": 6,
              "width": 24,
              "y": 18,
              "x": 0,
              "type": "metric",
              "properties": {
                  "metrics": concat(
              [for i, name in "$list_names" :
               [ { "expression": name, "label": i, "id": i }]
              ],
              [for i, name in "$list_names" :   
                 ["abcd", "id":i]
              ]
               )
              
              }
            }
         ]
    })
    }