HashiCorp Terraform Associate (004) Question 144
Single answer5b Describe variable scope within modulesA team maintains a root Terraform configuration that deploys networking and calls a child module named "app". The root module defines variable "environment" {} and sets it in terraform.tfvars. Inside the child module, the team wants to use the same environment value to name resources. However, terraform plan fails in the child module because var.environment is undeclared there. What is the correct way to make the value available inside the child module?
- A
Declare
variable "environment" {}inside the child module and pass it from the root module usingmodule "app" { environment = var.environment }. - B
Reference the root module variable directly inside the child module with
root.var.environment. - C
Add
environmenttoterraform.tfvarsinside the root module only; all child modules automatically inherit root input variables. - D
Declare the value as an output in the root module, then read that output directly from the child module.
Show answer and explanation
Correct answer: A
Explanation
Terraform modules are intentionally isolated. Input variables are scoped to the module where they are declared, so a variable defined in the root module is not directly visible inside a child module. To share data with a child module, declare a corresponding variable in the child and pass the value explicitly in the parent's module block. This is a core Terraform design principle that keeps module interfaces clear and reusable. Likewise, .tfvars files set values for the root module's input variables only, and outputs are used to expose values from a module to its caller, not the other direction. This behavior is consistent with HashiCorp's module documentation and input variable/output value best practices.
- A. Correct.
Correct. In Terraform, each module has its own variable scope. A child module cannot automatically see variables declared in the root module. To use a value in the child, the child module must declare its own input variable, and the caller must explicitly pass the value through the
moduleblock, such asenvironment = var.environment. - B. Incorrect.
Incorrect. Terraform does not provide a way for a child module to directly reference a root module variable using syntax like
root.var.environment. Module boundaries are explicit, and data must be passed through inputs and outputs. - C. Incorrect.
Incorrect. Values in
terraform.tfvarsapply to input variables of the root module, not automatically to child modules. A common misconception is that tfvars values cascade into all modules, but child modules only receive values that are explicitly assigned in theirmoduleblock arguments. - D. Incorrect.
Incorrect. Outputs flow outward from a module to its caller, not inward from a parent to a child. A child module cannot consume a root module output directly. If the root already has the value, it should pass it as a module input instead.