Terraform — Optional Values
A quick article discussing the options for having optional values in your variables in Terraform.
Suppose we have the below variable definition;
variable "my_object" {
type = object({
id = number,
name = string,
description = string
})
description = "(Required) A required variable"
}
my_object defines 3 values, let's just assume id and name are required and description would be an optional value. How would you populate that variable? Well, the common answer could be;
my_object = {
id = 1234,
name = "my_name",
description = null
}
The issue however is that if you are dealing with nested or complex objects or lists of objects then defining null becomes very laborious (even more so if you have multiple optional values inside a nested list of objects!).
Now comes along a new approach that's not widely known just yet. Since Terraform v0.15, it now has native experimental
support for optional() values! But how you ask? It's nice and simple;
variable "my_object" {
type = object({
id = number,
name = string,
description = optional(string)
})
description = "(Required) A required variable"
}
To enable this, you will need to add the experiment module_variable_optional_attrs to your terraform block; an example is below:
terraform {
required_version = ">= 0.15.0"
required_providers {
google = {
source = "hashicorp/google"
version = ">= 3.50"
}
}
experiments = [module_variable_optional_attrs]
}
By default, optional() sets the value of the field to be null however, there’s also another handy function called defaults() which handles object & collection types if you want to set default values to something other than null.
I have included the documentation links for these new function calls below, happy reading 😊!
Optional function — Terraform docs.
Defaults function — Terraform docs.
Disclaimer: Since the functionality is experimental, it is subject to change and would wait for the official release of these functions before using them in production workloads.