You've successfully subscribed to Nuvotex Blog
Great! Next, complete checkout for full access to Nuvotex Blog
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

terraform - use nullable in variables for default values

Writing terraform makes it easy to split code into modules. To avoid setting default values on each layer of the stack, use nullable to provide a way to fallback to the module's own default value.

Daniel Nachtrub
Daniel Nachtrub

Imagine the following project structure

-- myModule
project structure

The module's 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 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:


Daniel Nachtrub

Just some guy working with computers.