
| Source Type | Common Example |
|---|---|
| Terraform Registry | terraform-aws-modules/vpc/aws |
| Git repository | git::https://github.com/example/terraform-modules.git//vpc |
| Local path | ./modules/vpc |
Parent (root / calling) module — module block example
The root module uses amodule block to declare which child module to include and passes inputs to that child via variables.
- The module block name (
"vpc") is a local identifier; name it for clarity (for exampleproduction_vpcordev_vpc). sourcetells Terraform where to fetch the child module. It accepts registry paths, git URLs, or local filesystem paths (commonly./modules/<name>).- The keys on the left side of
=must match variable names defined by the child module. Values on the right can be literals, references (e.g.,var.x), or expressions.
Modules can come from the Terraform Registry, a Git repository, or a local path (place local modules under a
modules/ directory). Run terraform init to download remote modules into the working directory.Child module — structure, variables, resources, and outputs
A child module is just a normal Terraform configuration intended to be parameterized. Typical child module files:| File | Purpose |
|---|---|
variables.tf | Declare inputs the module accepts |
main.tf or resources.tf | Define resources created by the module |
outputs.tf | Export values for the parent or other modules to consume |
providers.tf (optional) | Configure provider requirements (use cautiously) |
variables.tf for a simple VPC child module:
main.tf (resource implementation) inside the child module:
outputs.tf in the child module:
How root and child modules connect
- The root module declares a
moduleblock and assigns values to the child module’s variables. - The child module uses those values to create resources.
- The child module exposes outputs that the root (or other modules) can reference.
module.prod_vpc.vpc_idreferences thevpc_idoutput exported by the child module namedprod_vpc.- Running
terraform initdownloads remote modules. Runningterraform applyprovisions resources in the child module and makes outputs available to the parent.
Passing values between modules
To wire modules together, the root module can forward outputs from one child module into another child module’s inputs.- Root module orchestrates and wires modules together.
- Child modules implement individual resources and expose outputs.
- Outputs allow values (like IDs) to be shared across modules.
Benefits of a modular approach
- Reuse: Build once, reuse across environments and projects.
- Separation of concerns: Each module focuses on a single responsibility.
- Maintainability: Smaller modules are easier to test and update.
- Consistency: Shared modules help enforce standard configurations.