terraform - use nullable in variables for default values

Imagine the following project structure

modules
-- myModule
----- main.tf
----- variables.tf
main.tf
variables.tf
project structure

The module's variables.tf provides several settings with appropriate default values. You want enable the caller of the parent module to be able to set custom values for the module's variables.

Like an example: The module myModule creates an AKS for you and applies a default SKU for the default nodepool. The module myModule provides a reasonable default value and you don't want to state another default value in the main module.

The solution here is very simple:

variable "aks_defaultPoolSku" {
  type        = string
  description = "SKU for the default nodepool"
  default     = "Standard_D2a_v4"
  nullable    = false
}
variable definition

By setting nullable=false terraform will - whenever a null value is provided utilize the default value. So, when calling myModule from main.tf it could look like this:

module "myModule" {
  for_each           = var.clusters
  ...
  aks_defaultPoolSku = try(each.value.defaultPoolSku, null)
  ...
}
call myModule with fallback

This example is iterating over a map and whenever the map has not specified the key defaultPoolSku it will provide a null value to the variable which will in turn apply myModule's default.

tfversion nullable requires terraform >= 1.1.0

So, that's quite easy. For more details, check out the terraform docs: https://www.terraform.io/language/values/variables#disallowing-null-input-values