Cheat Sheet 5: Terraform Modules
Basics: a module is a directory of .tf files. The root module is the working directory. Child modules are called with module blocks.
Sources (source must be a literal string)
| Type | Form | Pin with |
|---|---|---|
| Local | ./path or ../path (prefix required) |
— (read in place) |
| Public registry | NAMESPACE/NAME/PROVIDER |
version |
| Private registry | HOST/ORG/NAME/PROVIDER |
version |
| GitHub, Bitbucket | github.com/org/repo, bitbucket.org/org/repo |
?ref= |
| Git | git::https://… or git::ssh://… |
?ref= (tag or SHA; ?depth=1 for shallow) |
| Mercurial, HTTP, S3, GCS | hg::, https://…zip, s3::, gcs:: |
— |
Use //subdir to select a subdirectory in a package, for example repo.git//modules/vpc?ref=v1.0.0.
Installation
initdownloads modules to.terraform/modules/and records them inmodules.json.terraform get(-update) fetches modules only.- Re-init after adding a module block or changing
source,version, orref. Editing a local module's code doesn't need init.
Scope
- Parent → child: arguments in the
moduleblock set the child's variables. - Child → parent:
outputblocks, read asmodule.NAME.OUT, ormodule.NAME["key"].OUTwithfor_each. - The child can't see the parent's variables, locals, or resources. The parent can't see the child's resources.
TF_VAR_and.tfvarsset root variables only.
Module meta-arguments: count · for_each · providers = { aws = aws.west } (aliases must be passed; defaults are inherited) · depends_on (the whole module waits). No lifecycle on modules.
Refactoring: moved { from = old_addr to = module.m.new_addr } keeps the object and avoids a destroy and recreate.
Versions
- Same operators as providers.
~> 2.1→ ≥ 2.1.0, < 3.0.0. versionworks on registry sources only. Git uses?ref=.init -upgradere-resolves to the newest allowed version.- The lock file doesn't record modules.
- Pin production code. Never pin a Git source to a moving branch.
Writing modules: main.tf, variables.tf, outputs.tf, versions.tf (>= provider minimums), README.md, examples/, modules/. Don't put provider blocks in reusable modules.
Publishing to the public registry: a public GitHub repo named terraform-<PROVIDER>-<NAME>, semantic version tags, and the standard structure.
Module 5 self-check
Module 5 self-check.
- Coverage: 5a (lesson 5.1, lab steps 1, 6, and 8, Q1–Q3, Q6), 5b (lesson 5.2, lab steps 4–5, Q4–Q5), 5c (lesson 5.3, lab Part 3, Q7, Q10), and 5d (lesson 5.4, lab steps 9–10, Q8–Q9).
- HCL: every lab file uses valid arguments with
fmtalignment. Themovedaddresses match the module's resource names andfor_eachkeys.path.rootkeeps file paths identical across the refactor, so the plan shows moves, not replacements. - Error messages are paraphrased where wording varies by patch release.
- Answers are rechecked against documented module-source, scope, and version behavior.