Terraform 33: Terraform Modules 1: Using a module
easy⏱ 5 mincourseterraform
Calling a module
A module block wraps another configuration. source says where it lives; every other argument is an input variable the module declares. Terraform treats the module as a single node in the graph — plan/apply flow through it like any resource.
module "orders_fn" {
source = "./modules/function-app"
# inputs the module declares as variables
app_name = "orders"
environment_name = "dev"
location = "westus2"
subnet_id = azurerm_subnet.apps.id
}
Read outputs with module.<name>.<output>
A module only exposes what it declares as outputs. From the caller you reference them as module.orders_fn.function_id — you cannot reach a resource inside the module directly. Outputs are the module's public API.
# The module declares: output "function_id" { value = azurerm_linux_function_app.fn.id }
# The caller consumes it:
resource "azurerm_role_assignment" "reader" {
scope = module.orders_fn.function_id
role_definition_name = "Reader"
principal_id = var.pipeline_object_id
}
terraform init downloads modules
After adding or changing a module block you must run terraform init again — that's when Terraform fetches/links the module into .terraform/modules. Forgetting this yields a Module not installed error on plan.
Build a module output reference
Write moduleOutputRef(moduleName, output) that returns the caller-side reference string module.<moduleName>.<output>. Log moduleOutputRef("orders_fn", "function_id") — it should print module.orders_fn.function_id.