Difference between map and map object in terraform
Asked Answered
K

1

9

I was looking through the difference between map and object. My understanding is as follows :

A map can contain any type as long as all the elements are of the same type

variable "project_defaults" {
      type = map(string)
      default  = {
          project = "example_project"
          region = "eu-west-1" 
      }
    }

An object contains named attributes , each having their own type

variable "s3_buckets" {
  type = object({
    name       = string
    versioning = bool
    s3_rules   = list(map(any))
  })
  description = "List of maps for S3 buckets"
}

I have seen examples where map(object) is used but am really unsure what the difference is compared to the type object

variable "s3_buckets" {
      type = map(object({
        name                   = string
        versioning             = bool
        s3_rules   = list(map(any))
      }))
      description = "List of maps for S3 buckets"
    }

Am trying to make sense of when to make use of map(object) as opposed to using object . Syntax wise they look very similar but am unsure of the actual scenarios of when to use them.

Khajeh answered 11/3, 2023 at 15:6 Comment(0)
K
3

A map can contain any type as long as all the elements are of the same type. This makes sense if I have a map of just strings and want to make use of the values for whatever resource configuration.

The schema for object types is { <KEY> = <TYPE>, <KEY> = <TYPE>, ... } — a pair of curly braces containing a comma-separated series of <KEY> = <TYPE> pairs. Values that match the object type must contain all the specified keys, and the value for each key must match its specified type. This makes sense if a specific structure of the object schema needs to be followed when creating a resource.

One thing to note is that a map (or a larger object) can be converted to an object if it has at least the keys required by the object schema. Any additional attributes are discarded during conversion, which means map -> object map conversions can be lossy.

Khajeh answered 11/3, 2023 at 15:15 Comment(2)
Thanks to Terraform's implicit conversion, you can have map(string) or map(any) with string, number, and bool values.Plasterwork
This answer has nothing to do with map(object) which is what you seem to be asking in your question. map(object) is just a map of objects, similar to how map(string) is a map of strings. You can also have things like map(map(string)) which is a map of maps of strings for example. map(object) isn't doing some sort of type conversion.Extremely

© 2022 - 2024 — McMap. All rights reserved.