n0zz
n0zz

Reputation: 327

Default map values

Does the default value of the variable map merge 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?

Upvotes: 11

Views: 24606

Answers (2)

Martin Atkins
Martin Atkins

Reputation: 74064

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 provided or to local.foo to get the result of merging the caller's map with your map of default values.

Upvotes: 13

Snowcrash
Snowcrash

Reputation: 86057

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"

Upvotes: 1

Related Questions