'Terraform default map values

Does the default value of the variable map merges with data I provide to the terraform?

Sample variables.tf:

variable "foo" {
  type = map
  default = {
    lorem = "ipsum"
    dolor = "sit"
  }
}

And foo.tfvars provided:

foo = {
  dolor = "changed"
  amet = "consectetur"
}

Will ${foo.lorem} still exist?

Will ${foo.dolor} be "changed"?

Will ${foo.amet} be available?



Solution 1:[1]

No, there is no merging behavior. If you set an explicit value for a variable then the default is not used at all.

If you need to merge with other values then you can use the merge function to write that explicitly:

variable "foo" {
  type    = map(string)
  default = {}
}

locals {
  foo = merge(
    tomap({
      lorem = "ipsum"
      dolor = "sit"
    }),
    var.foo,
  )
}

With the above configuration, elsewhere in the module you can refer either to var.foo to get the exact value the caller provider or to local.foo to get the result of merging the caller's map with your map of default values.

Solution 2:[2]

Just to clarify, if you'd specified your tfvars file, you'd get:

${foo.lorem} = "Error: Missing map element"

${foo.dolor} = "changed"

${foo.amet}  = "consectetur"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Atkins
Solution 2