Terraform default map values

Viewed 8426

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?

2 Answers

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.

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"
Related