Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining Partial Default Values

Tags:

terraform

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.

like image 255
dingo Avatar asked Sep 16 '25 12:09

dingo


1 Answers

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.

like image 187
dingo Avatar answered Sep 19 '25 07:09

dingo