Terraform - override a single value in a map

Viewed 1257

I would like to know if it is possible to merge two map of maps without replacing the main map object.

My map object is defined as follows:

variable "apps" {
type = map(object({
 is_enabled    = bool
 cost_center   = string
}))
default = {}
}

locals {
  default_apps = {
    "api-1" = {
       is_enabled   = false
       cost_center  = "1234"
    },
    "api-2" = {
       is_enabled   = false
       cost_center  = "1235"
    },
  }
  apps = merge(
    local.default_apps,
    var.apps
  )
}

If define my tfars as follows, to override the value of api-1['s_enabled']

  apps = {
    "api-1" = {
      is_enabled   = true
    }
  }

I get the following error:

Error: Invalid value for input variable

The environment variable TF_VAR_apps does not contain a valid value for
variable "apps": element "api-1": attribute "cost_center" is required.

It works if I define my tfvars like so:

  apps = {
    "api-1" = {
      is_enabled   = true
      cost_center  = "1234"
    }
  }

My goal is to override a single value of one of the pre defined local variables under default_apps (e.x is_enabled) in tfvars.

Edit: requirements

1 Answers

The error is not about your merge but about your tfars. The following variable is invalid in your case:

  apps = {
    "api-1" = {
      is_enabled   = true
    }
  }

as you explicitly defined it as:

type = map(object({
 is_enabled    = bool
 cost_center   = string
}))

Your apps is missing cost_center which is required. If you use object type, everything that you specify in type definition must be provided:

Values that match the object type must contain all of the specified keys, and the value for each key must match its specified type.

Related