How to extract data as a List from Set with dynamic keys in terraform

Viewed 324

I have below set in terraform (which is extracted from data module)

{
   key1 {
     id = "5"
     name = "A"
   },
   key2 {
     id = "6"
     name = "A"
   }
}

keys are dynamic, and it will be n number of them, any value.

How can I get the below result? Please notice it's List of strings

[
  "5",
  "6"
]

I tried below, but it says Unsupported attribute

output "email_channels_keys" {
  value = var.emails.*.id
}
1 Answers

We can use a for lambda expression to iterate on the map(object)) and extract the value for the id key in the object within each map:

output "email_channels_keys" {
  value = [ for key, value in data.data_name.block_name.attribute : value.id ]
}

We use a list constructor to instantiate the type as a list. We then iterate over the map and store the string key in the temporary lambda scope variable key, and the object value in the temporary lambda scope variable value. We then access the value of the id key within the object with the normal usage of .id (["id"] is also valid syntax, but conventionally map values are accessed with ["<key>"] and object values with .<key> syntax). The returned value is assigned to email_channels_keys in your outputs.

Note that for your specific use case, you will need to update the data namespace for your specific data that you reference at the beginning of the question, and you may want to update key and value variables for more specific names.

Related