Module Sources and Versioning

Modules can come from local paths, Git, or the Terraform Registry, and registry modules should be pinned to a version.

Syntaxsource = "terraform-aws-modules/vpc/aws" version = "~> 5.0"

The source argument accepts several kinds of location.

Source types

  • Local path./modules/vpc for modules in your repo.
  • Terraform Registryterraform-aws-modules/vpc/aws, the public catalog of community modules.
  • Gitgit::https://github.com/org/repo.git.

Pin your versions

For registry and Git modules, always set a version constraint (or a Git tag) so an upstream change cannot break your infrastructure unexpectedly.

Example

Example · hcl
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"

  name = "soundscode-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["us-east-1a", "us-east-1b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]
}

When to use it

  • A team references an internal module from a Git URL with a ?ref=v1.2.0 tag, pinning the exact version while still hosting the module in their private GitLab.
  • An organization publishes vetted modules to the Terraform Registry with semantic versions so application teams can use version = '~> 3.0' for minor upgrades only.
  • A developer iterates on a local module during development using source = '../modules/vpc' and only pushes to Git after tests pass.

More examples

Local path source

References local modules by relative filesystem path, suitable for modules in the same repository.

Example · hcl
module "vpc" {
  source = "./modules/vpc"  # relative path
}

module "db" {
  source = "../shared/modules/rds"  # parent directory
}

Git source with pinned ref

Pulls a module from a private Git repository at a specific tag, ensuring the version is stable and auditable.

Example · hcl
module "vpc" {
  source = "git::https://github.com/my-org/tf-modules.git//modules/vpc?ref=v2.3.0"
}

# SSH alternative:
# source = "git::[email protected]:my-org/tf-modules.git//modules/vpc?ref=v2.3.0"

Terraform Registry source

Uses the standard Registry source format with a pessimistic constraint operator to allow minor-version upgrades only.

Example · hcl
# Format: <namespace>/<module>/<provider>
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"
  azs  = ["us-east-1a", "us-east-1b", "us-east-1c"]
}

Discussion

  • Be the first to comment on this lesson.