Claus-Theodor Riegg
1 year
Moritz Kraus
1 year
Claus-Theodor Riegg
1 year
Stefan Xenopol
1 year
Claus-Theodor Riegg
8 years

Use Terraform grouping mode like Golang's Ellipsis expression

Posted . Visible to the public.

The terraform documentation states the ... syntax as (grouping mode*. See: Grouping-Results Show archive.org snapshot ).

But this seems not the be the whole truth. Instead the ... syntax behaves like Go's Ellipsis expression which is used to pass a list as multiple parameters to a Variadic Function Show archive.org snapshot .

You can use this behavior for example if you want to merge a list of maps into one map:

locals {
  list_of_maps = [
    {
      "key1" = "value1"
      "key2" = "value2"
    },
    {
      "key2" = "new_value2"
      "key3" = "value3"
    },
    {
      "key4" = "value4"
    }
  ]
  
  merged_map = merge(
    [for map_item in local.list_of_maps: map_item]...
  )
}

output "merged_map" {
  value = local.merged_map
}

Note

This only works when a for expression is used. You can't use merged_map = merge(local.list_of_maps...) because the grouping mode is only available for for expressions.

This can be especially useful when creating data structures in loops:

  users = {
    users = {
    "Bob.Bobster" = {
      name = {
        given_name = "Bob"
        family_name = "Bobster"
      }
      email = "bob.bobster@foobaringen.com"
      group_memberships = ["GlobalAdministrators"]
    },
    "Alice.Charles" = {
      name = {
        given_name = "Alice"
        family_name = "Charles"
      }
      email = "alice.charles@foobaringen.com"
      group_memberships = ["GlobalAdministrators"]
    },

  }
  
  group_memberships = merge([
    for user, user_config in var.users : {
      for group in user_config.group_memberships :
      "${user}_${group}" => {
        user_id  = aws_identitystore_user.this[user].user_id
        group_id = aws_identitystore_group.this[group].group_id
      }
    }
  ]...)
Claus-Theodor Riegg
Last edit
Marius Schuller
Keywords
devops
License
Source code in this card is licensed under the MIT License.