Show answerHide answer
Correct answer: C Declare the output in both the root and child module
Explanation
Explanation:Terraform modules encapsulate their details. Just because a value exists within a module does not mean it is automatically available to the root module or the CLI. You must explicitly expose it.
Here is the required two-step process:
Step 1: Declare the output in the child module (Option B is part of the solution) Inside the child module's configuration (e.g., in a file like modules/network/outputs.tf), you must define an output block for any value you wish to expose.
Example (modules/network/outputs.tf):
hcl
# This makes the VPC ID available to the calling module.
output "vpc_id" {
value = aws_vpc.main.id
description = "The ID of the created VPC"
}
Purpose:
This makes the value available at the boundary of the child module. Without this step, the value is completely hidden and inaccessible from the outside.
Step 2: Declare the output in the root configuration (Option A is part of the solution) In your root module (e.g., in main.tf or outputs.tf), you first call the child module using a module block. Then, to display the value in the CLI, you must create a new output block in the root that references the output you exposed in Step 1.
Example (root module's outputs.tf):
hcl
# This captures the output from the child module and makes it a root-level output.
output "child_vpc_id" {
value = module.network.vpc_id # References the child module's output
description = "The VPC ID output from the network child module"
}
Only after completing both steps will the value be displayed in the Terraform CLI after running terraform apply or terraform output.
Why the Other Options Are Incorrect
A. Declare the output in the root configuration
Incorrect (on its own). You cannot declare an output in the root for a value that has not been exposed by the child module. The root module has no inherent visibility into the child module's internal resources. The syntax module.NAME.OUTPUT would fail because the OUTPUT would not be defined.
B. Declare the output in the child module
Incorrect (on its own). Declaring an output in the child module only makes it available for the calling module (the root) to use. It does not automatically print the value to the CLI. The value must be "passed through" by being referenced in a root-level output block to be visible in the command line.
D. None of the above
Incorrect. This is false because the correct and required method is a combination of options A and B, which is explicitly provided as option C.
References
This question tests a fundamental concept of module composition in Terraform, which is covered in the HashiCorp Terraform Associate 003 exam objectives under the domain:
4.0 Read, generate, and modify configuration
4.3 Use collections and structural types in configuration.
(Implicitly) Understand module outputs.