Terraform Modules
Introduction
This lesson covers the Terraform modules area of the Terraform Associate (004) exam, objectives 5a to 5d. The area holds four of the 37 objectives, about 11% of this course's mock questions (HashiCorp does not publish domain weights; that proportion is an OnLevelUp choice). The exam lasts one hour, tests Terraform 1.12, and mixes true/false, multiple-choice and multiple-answer questions. Note that the official certification page lists objective 5a (module sources) while the exam content list focuses on the other three; this course covers all four so that nothing is missed.
Once a configuration grows beyond a few resources, copy-paste becomes the enemy. A company that runs three environments (dev, staging, prod) in two regions does not want six slightly different copies of the same network code. A module is the answer: a reusable, parameterised package of Terraform configuration.
After this lesson you will be able to explain what a module is, load modules from local paths, the Terraform Registry and version control, pass values in and read values out, reason about variable scope, and pin module versions safely.
Learning objectives
- Define a root module and a child module, and explain why modules exist.
- Choose and write the correct
sourcefor local, registry, Git and other remote modules. - Explain variable scope: why a child module cannot see parent variables and how data flows through inputs and outputs.
- Call modules with
count,for_each,providersanddepends_on. - Version modules with
version(registry) or aref(Git), and understand howterraform initandterraform getinstall them.
5a. Module sources
Every Terraform configuration is a module. The directory where you run terraform plan is the root module. A child module is any module called from another with a module block. A module is simply a directory containing .tf files; there is nothing to register or compile.
module "network" {
source = "./modules/network"
cidr_block = "10.0.0.0/16"
environment = "prod"
}The source argument is mandatory and must be a literal string (no variables, no expressions), because Terraform installs modules during terraform init, before any variable is evaluated.
Supported source types
| Source type | Example source |
Versioning | Notes |
|---|---|---|---|
| Local path | ./modules/network or ../shared/vpc |
None, always the current files | Must start with ./ or ../. Not copied: Terraform uses the files in place |
| Terraform Registry (public) | hashicorp/consul/aws |
version argument |
Format <NAMESPACE>/<NAME>/<PROVIDER> |
| Private registry (HCP Terraform) | app.terraform.io/acme/network/aws |
version argument |
Format <HOSTNAME>/<ORG>/<NAME>/<PROVIDER> |
| GitHub | github.com/acme/terraform-aws-network |
Git ref |
Shorthand for HTTPS or SSH cloning |
| Generic Git | git::https://example.com/vpc.git?ref=v1.2.0 |
Git ref (tag, branch, commit) |
Prefix git:: forces Git |
| Bitbucket | bitbucket.org/acme/network |
Git ref |
Shorthand |
| HTTP URL | https://example.com/vpc-module.zip |
None built in | Archive downloaded and extracted |
| S3 bucket | s3::https://s3-eu-west-1.amazonaws.com/acme-modules/vpc.zip |
Object version in the path | Uses AWS credentials |
| GCS bucket | gcs::https://www.googleapis.com/storage/v1/acme-modules/vpc.zip |
Object path | Uses Google credentials |
Useful details:
- A subdirectory of a remote repository is addressed with a double slash:
git::https://example.com/infra.git//modules/vpc?ref=v2.0.0. - Registry modules are the easiest to consume: they have documentation, an inputs/outputs list, and semantic versions.
- A local module is the best choice while you are still designing the module, or when it is only used inside a single repository.
Worked example: choosing a source
Scenario. A platform team at a retail company maintains a VPC module used by 14 application teams in separate Git repositories. They want teams to upgrade deliberately, review changes and be able to roll back.
Reasoning, step by step.
- A local path (
../shared/vpc) would only work if all 14 repositories were checked out next to each other. Not realistic. - The module must be versioned, so the source must support versions: a registry or Git with
ref. - If the company has an HCP Terraform organization, the private registry gives semantic versions, a
versionconstraint syntax and generated documentation. - Without it, a Git repository with release tags (
ref=v1.4.0) offers the same pinning at the cost of no constraint operators: arefis an exact tag, branch or commit.
Solution.
module "vpc" {
source = "app.terraform.io/retailco/vpc/aws"
version = "~> 1.4"
cidr_block = "10.20.0.0/16"
}Why not the alternatives. A branch ref=main changes under your feet. A zip file over HTTP has no version semantics. A local path cannot be shared across repositories.
How modules are installed
terraform init downloads every remote module into .terraform/modules/ and records them in .terraform/modules/modules.json. Local modules are not copied. If you add a new module block, change a source, or change a version, run terraform init again (terraform init -upgrade to move to the newest version allowed by constraints). Until then, terraform validate and terraform plan fail with "Module not installed". The older terraform get command only downloads modules and does not install providers or configure backends.
5b. Using modules in configuration: inputs, outputs and scope
Inputs
A child module declares its inputs with variable blocks. The caller sets them as arguments inside the module block.
# modules/network/variables.tf
variable "cidr_block" {
type = string
description = "CIDR block for the VPC."
}
variable "environment" {
type = string
default = "dev"
}
# modules/network/main.tf
resource "aws_vpc" "this" {
cidr_block = var.cidr_block
tags = { Environment = var.environment }
}
# modules/network/outputs.tf
output "vpc_id" {
value = aws_vpc.this.id
}A variable without a default is required: terraform init or plan fails if the caller omits it.
Outputs
The parent reads child values as module.<NAME>.<OUTPUT>:
module "network" {
source = "./modules/network"
cidr_block = "10.0.0.0/16"
environment = "prod"
}
resource "aws_security_group" "web" {
name = "web"
vpc_id = module.network.vpc_id
}
output "vpc_id" {
value = module.network.vpc_id # re-export if the root should show it
}Only outputs declared in the child module are visible. The child's resources, locals and variables are not reachable from outside, even from its parent. This encapsulation is the whole point.
Variable scope
The scope rules are simple and heavily tested:
| Question | Answer |
|---|---|
| Can a child module read a variable declared in the parent? | No. Each module has its own variables namespace |
| Can a child module use a resource from the parent? | No, unless the parent passes an attribute as an input |
| Can the parent read a child's resource attribute? | Only if the child exposes it with an output |
| Can the parent read a child's local value? | No. Locals are private to the module |
| Are root module variables set the same way as child inputs? | No. Root variables come from -var, .tfvars, TF_VAR_* or HCP Terraform; child inputs come from the module block |
Because data flows only through declared inputs and outputs, you can reuse the same module in many contexts without worrying about name clashes.
Meta-arguments on modules
A module block accepts count, for_each, depends_on, providers and (since Terraform 1.x) version/source. The first two create several instances:
module "bucket" {
source = "./modules/s3-bucket"
for_each = toset(["logs", "backups", "exports"])
name = "acme-${each.key}"
}
output "bucket_arns" {
value = { for k, m in module.bucket : k => m.arn }
}Instances are addressed as module.bucket["logs"]. Changing the keys later adds or destroys only the affected instance.
Providers and modules
By default a child module inherits the default provider configuration of its parent. To use a non-default or aliased configuration, pass it explicitly:
provider "aws" {
alias = "paris"
region = "eu-west-3"
}
module "dr_site" {
source = "./modules/site"
providers = {
aws = aws.paris
}
}Inside the module, a required_providers block declares which providers it needs, and configuration_aliases lets it accept extra aliases. Best practice: do not put provider blocks inside reusable modules. A module that contains its own provider block cannot be removed with count or for_each easily, because Terraform needs the provider to destroy the resources.
Worked example: refactoring duplicated code into a module
Scenario. A startup has two almost identical blocks creating a storage bucket with versioning for prod and staging. The staging bucket must not have versioning, to save cost.
Step by step.
- Create
modules/bucketwith variablesname(string) andversioning(bool, defaulttrue). - Move the
aws_s3_bucketandaws_s3_bucket_versioningresources into the module and replace literals withvar.nameandvar.versioning. Usecount = var.versioning ? 1 : 0on the versioning resource. - Add
output "arn"andoutput "id". - Replace the two resource groups with two
moduleblocks. - Because the addresses have changed (
aws_s3_bucket.prodbecomesmodule.prod_bucket.aws_s3_bucket.this), addmovedblocks so Terraform does not destroy and recreate the buckets.
Solution (root module).
module "prod_bucket" {
source = "./modules/bucket"
name = "acme-prod-data"
versioning = true
}
module "staging_bucket" {
source = "./modules/bucket"
name = "acme-staging-data"
versioning = false
}
moved {
from = aws_s3_bucket.prod
to = module.prod_bucket.aws_s3_bucket.this
}Why other approaches are weaker. Copying the block a third time would repeat every future fix. Using terraform state mv also works but is manual and not reviewable in a pull request; a moved block is declarative and versioned with the code.
5c. Module versioning
Unversioned modules make builds non-reproducible: the same code applied tomorrow could create different infrastructure. Pin versions.
Registry modules: the version argument
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.8.1"
}The version argument accepts the same constraint syntax as providers:
| Constraint | Meaning |
|---|---|
"5.8.1" |
Exactly 5.8.1 |
">= 5.0" |
5.0 or newer, including a future 6.x |
"~> 5.8" |
5.8 or newer but below 6.0 (the rightmost component may increase) |
"~> 5.8.1" |
5.8.1 or newer but below 5.9.0 |
">= 5.0, < 6.0" |
A range with two conditions |
version works only with registry sources. For Git sources use ref; for local paths there is no version.
Git sources: ref
module "vpc" {
source = "git::https://github.com/acme/terraform-aws-vpc.git?ref=v1.4.0"
}ref accepts a tag, branch or commit SHA. Tags and commit SHAs are stable; a branch name moves. After you change a ref, run terraform init -upgrade or terraform init to refresh the download.
Why pin, and how to upgrade safely
- A plan against a module whose code changed can show unexpected replacements.
- The dependency lock file (
.terraform.lock.hcl) locks providers only. It does not lock module versions. Module versions are controlled byversionandref. - To upgrade: raise the constraint, run
terraform init -upgrade, read the plan carefully, then apply. Many teams run the upgrade in a non-production workspace first.
Publishing a module
To publish a module to the public registry the repository must be public on GitHub, named terraform-<PROVIDER>-<NAME> (for example terraform-aws-vpc), have a root module with main.tf, variables.tf and outputs.tf, and be released with a semantic-version tag such as v1.2.0. A private registry in HCP Terraform follows the same convention and also supports a no-code provisioning option.
5d. Module design and good practice
The exam content also expects you to know what a good module looks like:
- Keep the module focused: one clear purpose (a network, a database), not "everything for the project".
- Expose a small, typed interface: describe each variable, use
type, addvalidation, give sensible defaults to optional inputs. - Output what callers need: IDs, ARNs, endpoints. Mark sensitive outputs with
sensitive = true. - Do not hard-code provider settings or backend configuration inside reusable modules.
- Document: a
README.mdand examples; registry modules render the README and the inputs/outputs table. - Use the standard layout:
main.tf,variables.tf,outputs.tf,versions.tf.
# versions.tf in a reusable module
terraform {
required_version = ">= 1.9"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 5.0"
}
}
}The module declares the minimum it needs; the root module's lock file decides the exact provider version.
Comparison: root module and child module
| Aspect | Root module | Child module |
|---|---|---|
| Where it lives | The directory where you run Terraform | A directory referenced by a module block |
| Variables set by | CLI, tfvars, environment, HCP Terraform | Arguments in the module block |
| Backend configuration | Allowed (terraform { backend ... }) |
Ignored in practice; only the root decides |
| Provider configuration | Defined here | Inherits or receives via providers |
| State | Owns the state | Resources are part of the root state under module.<name> |
A key fact: modules do not have separate state files. Their resources live in the root module's state with addresses like module.network.aws_vpc.this.
Common pitfalls and exam tips
- Exam tip: a variable in the parent is invisible in the child. If a question says "the child module fails with an undeclared variable", the fix is an input in the
moduleblock. - Exam tip: you can only read child outputs.
module.network.aws_vpc.this.idis invalid; define an output. - Pitfall: putting a variable in
sourceorversion. Both must be literal. - Pitfall: forgetting to run
terraform initafter adding or changing a module. - Pitfall:
versionon a Git or local source. It is only valid for registry modules. - Pitfall: relying on the lock file to pin modules. It only pins providers.
- Exam tip: the registry source address has three parts: namespace, name, provider. A private registry address begins with the hostname.
- Pitfall: renaming a
moduleblock label without amovedblock, which destroys and recreates its resources.
Mini case study
Situation. A media company has a root configuration with this block:
module "db" {
source = "git::https://git.example.com/infra/terraform-aws-rds.git?ref=main"
name = "orders"
}A teammate complains that last Friday's plan showed a replacement of the database even though nobody changed the root configuration. The module also needs the aws.replica provider for a read replica in another region, but it fails with a provider error.
Questions. (1) Why did the plan change? (2) How do you fix it? (3) How do you give the module the replica provider?
Answer.
ref=mainpoints to a moving branch. The module authors pushed a breaking change tomain, andterraform init -upgrade(or a fresh checkout) pulled it.- Pin to a release tag, for example
?ref=v2.3.1, and move to newer versions deliberately: change the ref, runterraform init -upgrade, review the plan. - Define the aliased provider in the root and pass it with
providers = { aws.replica = aws.eu_west_3 }; inside the module declareconfiguration_aliases = [aws.replica]inrequired_providers.
Key terms
- Root module: the working directory where Terraform commands are run.
- Child module: a module called by another module.
- Source: the address from which Terraform fetches a module.
- Registry module: a module published with namespace, name and provider and versioned semantically.
- Input variable / output value: the only data channels in and out of a module.
providersmeta-argument: passes provider configurations to a module.movedblock: records that a resource address changed, avoiding replacement.
Summary checklist
- I know that every configuration is a module and the working directory is the root module.
- I can write sources for local paths, the registry, Git and other remote locations, and I know
sourcemust be literal. - I know
terraform initinstalls modules and must be re-run after changes. - I can explain that child modules cannot see parent variables and parents see only declared outputs.
- I can call a module with
countorfor_eachand pass providers. - I know
versionis for registry modules andrefis for Git, and that the lock file does not pin modules. - I know modules share the root module's state.
Official sources
- https://developer.hashicorp.com/terraform/language/modules (opens in a new tab)
- https://developer.hashicorp.com/terraform/language/modules/develop (opens in a new tab)
- https://developer.hashicorp.com/terraform/language/modules/sources (opens in a new tab)
- https://developer.hashicorp.com/terraform/language/block/module (opens in a new tab)
- https://developer.hashicorp.com/terraform/tutorials/certification-004/associate-review-004 (opens in a new tab)
