TF-Associate-004 - Terraform modules - Section 5b

Describe variable scope within modules.

A module receives values only through its input variables and exposes values only through its outputs; a parent cannot reach a child's internal resources directly. Candidates should reason about how values flow in and out and why encapsulation is the point of a module.

module input variablesmodule outputsencapsulationparent to child value flow

Practice question for this objective

Free sampleTerraform modulesmedium

A root module calls a child module named 'network' and passes a subnet CIDR to it. Inside the child module, the practitioner references a variable named 'cidr_block' that the root never sets. Terraform errors during plan. Given the code, what is the correct fix so the value flows from root to child?

# root main.tf
module "network" {
  source = "./modules/network"
  subnet_cidr = "10.0.1.0/24"
}
# modules/network/main.tf
resource "aws_subnet" "this" {
  cidr_block = var.cidr_block
}
  • ADeclare 'variable "cidr_block"' in the child module and pass 'cidr_block = "10.0.1.0/24"' in the module block, since the argument name must match the child's variable name. Correct
  • BAdd 'output "cidr_block"' to the child module so the root's 'subnet_cidr' argument is exported into the child's scope automatically.
  • CReference 'var.subnet_cidr' directly inside the child module, because child modules inherit the parent's variable names.
  • DSet 'TF_VAR_cidr_block' as an environment variable so the child module picks it up at plan time.
A child module receives values only through input variables whose names match the arguments given in its module block. Terraform passes values into a child module by matching each module-block argument to a variable declared inside that child. The child's var.cidr_block is only populated if a variable of that exact name is declared and an argument of that name is supplied.

Why A is correct: Correct: a child variable is set by an argument of the same name in the module block, so aligning the names lets the root value reach var.cidr_block.

Why B is wrong: Tempting because outputs relate to modules, but outputs expose child values to the parent; they do not import a parent argument into the child.

Why C is wrong: Plausible if you assume inheritance, but modules are encapsulated: a child cannot read a parent variable it has not been passed as an input.

Why D is wrong: Tempting since TF_VAR_ sets variables, but that mechanism only populates root module variables, not a nested child module's inputs.

See more TF-Associate-004 practice questions, answers explained.

More in this domain

Back to all Terraform modules objectives, or the TF-Associate-004 cert hub.

Examworthy is not affiliated with or endorsed by HashiCorp. Original, blueprint-aligned practice material only.