Is it possible to access the default value of a variable?

I am configuring an existing module. The module that is being configured declares a variable x with default value v. I do expose the same variable in my configuration but I would only like to declare it if the value changes from its default. Trying the code below causes errors when the variable is not defined.

 module "mod" {
      source = "git://...."
     x = var.config.x
}

I would like x to be assigned if and only if I do have it declared in my config. Otherwise assign its default value. I don’t want to explicitly repeat the default value in my code because should the default value in the module change this would create confusion.

Therefore, I am looking for something like:

    x = try(var.config.x, default(module.x))

Is there any way to achieve this?

Hi @hyp0th3rmi4,

If you are using Terraform v1.1.0 or later then you could potentially make use of the new ability to declare a variable as “non-nullable”, which for optional variables (those which have a default) means Terraform will treat assigning null in the same way as omitting the argument, allowing the default to be chosen in both cases.

Inside your module you’d declare variable "x" like this:

variable "x" {
  type     = string # or whatever makes sense
  default  = "hello"
  nullable = false
}

Then in the calling module block, you can conditionally set the value to null, which will cause Terraform to use the default value declared inside the module:

module "mod" {
  source = "git://...."

  x = try(var.config.x, null)
}

This is a little different than what you asked for, in that it doesn’t allow the calling module to actually access the default, but if I understood your underlying goal correctly I think it will meet it in a different way, by allowing the calling module to dynamically choose to leave the value unset so that the child module itself can substitute in the declared default value.

Thanks very much, that is exactly what I need. I think the version of terraform we are running is way lower than 1.1.0. Hence, I have for now added the explicit default value to the module configuration. But it is good to know that this matter has been taken care of.