Module 5: Terraform Modules

Lesson 5.1: How Terraform Sources Modules

Plain language

A module is a directory of .tf files. Every configuration has one root module, which is the working directory where you run Terraform. A root module calls child modules with module blocks. The source argument tells Terraform where the child module's code lives.

Source types

Source type Example source value version argument?
Local path "./modules/site" or "../shared/network". Must start with ./ or ../ ✗
Public Terraform Registry "terraform-aws-modules/vpc/aws", in the form <NAMESPACE>/<NAME>/<PROVIDER> ✓
Private registry (HCP Terraform or Enterprise) "app.terraform.io/acme-corp/vpc/aws", in the form <HOSTNAME>/<ORG>/<NAME>/<PROVIDER> ✓
GitHub "github.com/acme/terraform-site" (HTTPS) or "git@github.com:acme/terraform-site.git" (SSH) ✗, use ?ref=
Bitbucket "bitbucket.org/acme/terraform-site" ✗, use ?ref=
Generic Git "git::https://git.example.com/site.git?ref=v1.2.0" or "git::ssh://git@git.example.com/site.git" ✗, use ?ref=
Mercurial "hg::https://hg.example.com/site?ref=v1.2.0" ✗
HTTP URL "https://example.com/site-module.zip" ✗
S3 bucket "s3::https://s3-us-east-1.amazonaws.com/acme-modules/site.zip" ✗
GCS bucket "gcs::https://www.googleapis.com/storage/v1/acme-modules/site.zip" ✗

Source string details

  • Subdirectories: a double slash // selects a directory inside a package. For example, git::https://git.example.com/infra.git//modules/vpc?ref=v1.2.0.
  • Git refs: ?ref= accepts a branch, tag, or commit SHA. Pin to a tag or SHA for reproducibility. ?depth=1 requests a shallow clone.
  • Literal values only: source and version must be literal strings. You can't use variables or expressions in them.

Under the hood

  • terraform init downloads remote modules into .terraform/modules/ and records them in .terraform/modules/modules.json.
  • Local paths aren't copied. Terraform reads the files in place, so edits to a local module take effect on the next plan with no re-init.
  • terraform get downloads modules without the rest of init. terraform get -update re-checks remote sources.
  • Re-run init whenever you add a module block or change a module's source or version. This applies to local paths too, because init must register the new module call.