-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Allow better lookup default value for map of objects with optional attributes #35027
Description
Terraform Version
1.7.3Use Cases
I would like to provide a sane default lookup value for a map of objects with optional values.
My current specific use case:
I have a module that creates some AWS eventbridge schedules. I have a variable that I am using to allow consumers to override values of default schedules while at the same time providing custom schedules of their own.
Here's what it looks like right now:
variable "schedules" {
description = <<-DESC
EventBridge schedule overrides for the application.
These values will be merged with the default schedules or can create new schedules if no matching key is found.
DESC
type = map(object({
schedule_expression = optional(string)
description = optional(string)
enabled = optional(bool, true)
command = optional(list(string))
cpu = optional(number)
memory = optional(number)
}))
default = {}
}
locals {
default_schedules = {
schedule1 = {
schedule_expression = "cron(0 8 ? * 3 *)" # Every Tuesday at 8:00 AM
description = "Schedule 1"
enabled = true
command = ["command1"]
}
schedule2 = {
schedule_expression = "cron(0/15 * ? * * *)" # Every 15 minutes
description = "Schedule 2"
enabled = true
command = ["command2"]
}
}
# Merge default schedules with var.schedules
# If matching default schedule does not exist, create the provided schedule
schedules = {
for name in setunion(keys(var.schedules), keys(local.default_schedules)) :
name => merge(
try(local.default_schedules[name], {}),
{ for k, v in try(var.schedules[name], {}): k => v if v != null } # Remove null values that result from optional object values
)
}
}
I'm doing this to provide a flexible and easily configurable abstraction
Attempted Solutions
In my use case, note my usage of try(local.default_schedules[name], {})
I'm doing this because lookup(local.default_schedules, name, {}) does not work. I get an error: the default value must have the same type as the map elements
try seems like a suboptimal solution here because I don't want to swallow other unspecified errors unexpectedly or anything like that.
The solution suggested in the referenced issue also feels really unsatisfying. Fully specifying the entire object with null values is not something I'm going to do in this case.
Proposal
No response
References
This has been discussed a bit before, and it's said that this currently behaves as designed. That may be the case, but if so, I think the design should be changed to support a reasonable alternative.