How to refrence a dependancies variable description in terraform?

Viewed 15

When writing terraform modules, one is commonly writing pass through variables/inputs for dependent objects.

How can I write the variable so that the description/type just references the dependent description?

I imagine something like

variable "foo" {
  type = dependant.resource.foo.var.type
  description = dependant.resource.foo.var.description
  default = "module default"
}
1 Answers

Variable descriptions are metadata used by Terraform itself (specifically: by documentation mechanisms like Terraform Registry) and are not data visible to your module code.

Each module's input variables and output values must be entirely self-contained. Mechanisms like the Terraform Registry rely on this so that they are able to generate the documentation for a module only by reference to that module, without any need to fetch and analyze any other modules or other dependencies.

If you do intend to have a variable just "pass through" to a child module or to a resource configuration then you will need to redeclare its type and description in your module.


I would also suggest considering the advice in the documentation section When to write a module; directly passing through a variable to a child object isn't necessarily a wrong thing to do, but it can result from a module not raising the level of abstraction and therefore not passing the test described there.

In such cases, it can be better to use module composition instead of nested modules.

In this case would mean that the caller of your module would themselves call the other module you are currently wrapping. Instead of your module taking that other module's input variables as its own, it would be declared to accept the other module's output values as its input, so that the caller can pass the object representing the first module result into the second module:

module "first" {
  # ...
}

module "second" {
  # ...

  first = module.first
}

Inside this "second" module, the input variable first would be declared as requiring an object type with attributes matching whatever subset of the output values of "first" that the second module depends on.

Related