Read more

Use Terraform grouping mode like Golang's Ellipsis expression

Claus-Theodor Riegg
March 28, 2023Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more 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
March 28, 2023Software engineer at makandra GmbH
Posted by Claus-Theodor Riegg to makandra Operations (2023-03-28 09:24)