I am defining a variable in Terraform as:
variable 'var_a' {
type = object({
name = string
enabled = bool
})
default = {
name = "the_name"
enabled = true
}
}
If no value is passed to generate this variable, it would be populated with the values of "the_name" and true. However, I want to be able to still execute this code if only certain values of the variable object are provided.
For example, if I pass this as a variable:
var_a = {
name = "another_name"
}
I would still like the enabled attribute to be set to true, based on the default value. When I try to use this code, it fails as it is expecting me to declare the enabled attribute.
After some additional research, the answer for my case is to use the optional keyword (Optional Object Type Attributes).
This allows one to specify whether the variable object attribute is optional, and provide a default value for that optional attribute.
Using optional with regard to the example above would look like:
Variable Definition:
variable "var_a" {
type = object({
name = string
enabled = optional(bool, true)
})
}
Usage:
var_a = {
name = "another_name"
}
Variable Value:
{name = "another_name", enabled = true}
This yields the intended result for the variable, populating optional values with provided defaults.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With