Default values for submodules

Hi,

What would be the best way to define a default to submodule without having to redefine it?

module submodule {
  some_variable = var.some_variable
}

I want to be able to define var.some_variable in a way that it will be optional and defaults in whatever is default in submodule, without having to copy paste it.

Hi @vchepkov,

Achieving this effect requires cooperation from both the calling module and the called module.

Inside the called module you can declare this variable as being “non-nullable”, which means that in any situation where the value would be null Terraform will use the default value instead:

variable "some_variable" {
  type     = string
  default  = "example"
  nullable = false
}

(Without nullable = false Terraform assumes that null is a reasonable value for this variable to be assigned and so will not use the default value automatically in that case.)

In your calling module (the one containing the module block) you can then declare the default value for the caller’s version of this variable to be null:

variable "some_variable" {
  type    = string
  default = null
}

module "example" {
  source = "..."

  some_variable = var.some_variable
}

If the user of the calling module leaves some_variable unset or explicitly sets it to null then this module will pass null into the child module. The child module’s nullable = false will then cause that null to be replaced by "example" (the default value) inside the child module.

Thank you @apparentlymart

Unfortunately, most of the modules do not follow this pattern, take for example https://github.com/terraform-aws-modules/terraform-aws-eks/blob/master/modules/self-managed-node-group/variables.tf

It would be useful to turn nullable = false globally, so one doesn’t have to add it explicitly in every single variable

Hi @vchepkov,

It is up to the author of a module to decide how its arguments will be interpreted. If you know that a particular module does not accept null as a meaningful value for a particular argument then I would suggest proposing to the module author to set nullable = false to represent that.

Terraform does not offer features to allow you to change the definition of a module from outside of that module.