Strongly typing nested object

Hi.
I raised this in the following Github issue: Variable validation for nested objects within a map · Issue #31654 · hashicorp/terraform · GitHub however following the response there this may be a more general user question rather than a bug.
I’m trying to strongly type a nested object with the name of each object as the key.
I am using the following code:

variable "networks" {
  type = map(
    object({
      object({
        address_space = string
      })
    })
  )
  default = {
    "uksouth" = {
      "network1" = {
        address_space = "10.1.1.0/24"
      }
      "network2" = {
        address_space = "10.1.2.0/24"
      }
    }
    "northeurope" = {
      "network1" = {
        address_space = "192.168.1.1/24"
      }
      "network2" = {
        address_space = "192.168.2.0/24"
      }
    }
  }
}

output "networks" {
  value = var.networks
}

In this example uksouth being the location can be any value as well as the network name in the child object. When running plan on this I get the following error:

│ Error: Missing attribute value
│
│   on main.tf line 6, in variable "networks":
│    3:     object({
│    4:       object({
│    5:         address_space = string
│    6:       })
│    7:     })
│
│ Expected an attribute value, introduced by an equals sign ("=").

Is there any way to strongly type the nested objects in the variable definition? If I remove the type constraint the variable works as expected and I can access the data from the nested objects.

1 Like

Hi @adhodgson1,

From the example value you showed, it seems like you have a map of maps of objects, rather than a map of objects with other objects nested inside them.

If that’s true, then your type constraint should be like map(map(object({ ... to declare that.

If you want to use an object type then you need to specify exactly which attributes the object will contain, because that’s the main thing that distinguishes map types and object types: maps allow the keys to be dynamically chosen, while objects have a predefined static set of attributes declared as part of the constraint.

1 Like

Thanks that is really helpful and has done exactly what I wanted.