The Terraform documentation indicates this should already be happening:
https://www.terraform.io/docs/language/expressions/types.html
null: a value that represents absence or omission. If you set an argument of a resource or module to null, Terraform behaves as though you had completely omitted it — it will use the argument's default value if it has one, or raise an error if the argument is mandatory.
I'm calling a module "foo" that has the following variable file:
variable "bar" {
type = string
default = "HelloWorld"
}
Example 1
When I call it using this code:
module "foo" {
source = "../modules/foo"
bar = null
}
The result is an error. Invalid value for "str" parameter: argument must not be null. Trigger when bar is being used.
Example 2
When I call it using this code (omitting it, rather than nulling it):
module "foo" {
source = "../modules/foo"
# bar = null
}
The result is that it works. The "bar" variable is defaulted to "HelloWorld".
This appears to be a bug In Terraform that someone else also raised but wasn't resolved. https://github.com/hashicorp/terraform/issues/27730
Does anyone know a solution or a work around?
Version information:
Terraform v1.0.5
on linux_amd64
+ provider registry.terraform.io/hashicorp/google v3.51.0
+ provider registry.terraform.io/hashicorp/null v3.1.0
+ provider registry.terraform.io/hashicorp/random v3.1.0
+ provider registry.terraform.io/hashicorp/time v0.7.2
Workaround
Based on @Matt Schuchard's comment and some research there's a ugly solution using the conditional check:
variable "foo" {
type = string
default = "HelloWorld"
}
locals {
foo = var.foo == null ? "HelloWorld" : var.foo
}
Why
My use case is an attempt to avoid duplicated code. I have 2 very similar modules, one being a subset of the other. The solution I'm using is to put the modules in sequence calling each, i.e. a grandparent, parent and child.
I want to have the variables available to the "grandparent" but if they're omitted then the module below "child" should set them using a default value, e.g. "HelloWorld". But to exposed those variables all the way through the family line I have to include them in all modules and in the high modules (grandparent and parent) I want to default them to null, allowing them to be optional but also still causing them to be set to a default in the "child" further down the line.
...I think I need a diagram.