Map Object with Optional Attributes

Hey all, late to the party here. I faced this issue recently and I hope this can help anyone who finds this post.

The code below can normalize the parent map so that each child map can have the exact same key/value pairs.

locals {
  subnets_defaults = {
    "address_prefix" = ""
    "service_endpoints" = []
  }
  subnets_normed = {for k, v in var.subnets: k =>  merge(local.subnets_defaults,v)}
}

Add default values to the subnets_defaults map. A new normalized map (subnets_normed) will be created which can be used in for_each loops.

If any subnet map lacks one of the default properties, it will be added with the value specified in subnets_defaults. If the property already exists, it will be left as-is; existing properties have priority over defaults.

If you want default properties to have priority over existing, flip v and local.subnets_defaults in the merge function.

Note that Hashicorp is working on an experimental feature that does the same here. I prefer my way since it’s easier to implement.