Hi - thanks for giving us Terraform!!!
I posted this into a discussion thread on GitHub, but am adding it here too…
I would suggest that (though the v1.3.0 adding of the 2nd default field in the “optional()” function is an improvement) the “optional()” keyword/function itself is really a bit of a red-herring and simply expanding the variable structure to allow nesting would be a more natural and syntactically consistent approach.
The code would look something like this…
A normal simple variable declaration:
variable "name" {
type = string
description = "The name"
default = "blah"
}
A complex variable declaration:
variable "settings" {
description = "The settings for my widget"
type = object({
name = string # shorthand for "{ type = string }"
notes = { type = string, default = "Many things to do" }
how_many = { type = number, default = 1, description = "Count of items" }
list_of_items = { type = list, default = [] }
})
}
Just as with simple variables, the act of declaring a default makes it optional; there is no need for an “optional()” keyword/function and conversely not specifying a “default” makes it a required item.
Note that it also allows a description for each item in the object.
Thinking about it, the “object()” declaration could become redundant too, as the fact that there is a mix of types would implicitly make that so.
variable "settings" {
description = "The settings for my widget"
type = {
name = string # shorthand for "{ type = string }"
notes = { type = string, default = "Many things to do" }
how_many = { type = number, default = 1, description = "Count of items" }
list_of_items = { type = list, default = [] }
}
}
Extrapolating that further, the “type =” lines could be recursive and thus support sub-objects .