Learning Objectives
By the end of this chapter, you will be able to:
- Explain how Terraform sources modules from local paths, the public Terraform Registry, and git repositories, including sub-directory references and ref pinning.
- Describe variable scope within modules and the parent/child relationship, including why a child module cannot read a sibling or parent variable directly.
- Use modules in configuration by wiring inputs through arguments on the
moduleblock and consuming outputs through themodule.<name>.<output>reference syntax. - Manage module versions with the
versionargument, semver constraint operators, and explicit git refs, and recognise where each pinning mechanism is supported.
Executive Summary
- A module is any directory that holds Terraform configuration files; the directory you run
terraformagainst is the root module, and every other module called from it is a child module. - The
sourceargument on amoduleblock tells Terraform where to fetch the child module from: a local path, the public Terraform Registry, a git repository over HTTPS or SSH, an HTTP archive, or an object store, with optional//subdirand?ref=modifiers. - Variables are scoped per module. A child module only sees what the calling module passes in through arguments, and the calling module only sees what the child exposes through
outputblocks. - The
versionargument is honoured only for module sources that resolve through a registry (the public Terraform Registry or an HCP Terraform private registry). Git, local, and HTTP sources do not acceptversion; they are pinned through the source string itself.
Assumptions
- The reader is on Terraform 1.12 and uses the documented HCL syntax shipped with that release.
- Provider configuration, state, and the core write/plan/apply loop are already established from earlier chapters; this chapter does not redefine
provider,Terraform Core, the dependency lock file, or any term enumerated in the previous CONTEXT_OUTPUT blocks. - Examples avoid cloud-specific resources where possible. When a concrete provider is needed, the chapter uses a small set of generic providers (
random,null,local) so the syntax is the focus, not the cloud surface area.
