Skip to main content

Infrastructure as code · Intermediate · 22 min

Share a Terraform module between projects with versioned Git tags

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Terraform 1.17.2 · terraform-docs 0.25.1 · Git

You will publish a small Terraform module from its own Git repository, release it as v1.0.0, use it from another project pinned to that tag, then ship a breaking v2.0.0 and upgrade the caller on purpose.

On this page

Copying a folder of Terraform from one project to the next works until you fix a bug in one copy and forget the other four. A shared module fixes that: one repository holds the code, every project points at it, and each project chooses when to take a new release.

Git tags are the simplest way to do the choosing. A caller writes ?ref=v1.0.0 in the module's source address, and Terraform fetches exactly that tag, no matter what lands on the main branch afterwards. Version numbers follow semantic versioning: a major bump (1.x to 2.0.0) says "this will break your code", so callers upgrade when they are ready, not when you push.

In this tutorial you build a small naming-and-tagging module, the kind most teams end up writing so every resource gets the same name prefix and tags. You will:

  • lay the module out the way the Terraform Registry expects, with an examples/ folder
  • generate the README's inputs and outputs tables with terraform-docs
  • tag v1.0.0 and push it to a shared repository
  • use it from a second project with a git:: source pinned to the tag
  • make a breaking change, document it, and release v2.0.0
  • upgrade the caller deliberately and fix what the new version requires

To keep the tutorial free of accounts, a bare Git repository in ~/modules-demo/remote plays the part of GitHub or GitLab. Every command works the same against a hosted repository; only the URL changes. Nothing here creates cloud resources or bills.

Step 1 · Install Terraform 1.17, terraform-docs 0.25 and Git

Install the basics, then download Terraform 1.17.2 for your machine's architecture, check it against HashiCorp's checksums and install it:

Bash
sudo apt update
sudo apt install -y curl unzip git ca-certificates
ARCH=$(dpkg --print-architecture)
TF_VERSION=1.17.2
cd "$(mktemp -d)"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_${ARCH}.zip"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "terraform_${TF_VERSION}_SHA256SUMS"
unzip -o "terraform_${TF_VERSION}_linux_${ARCH}.zip" terraform
sudo install -m 0755 terraform /usr/local/bin/terraform
terraform version

terraform-docs reads a module's variables and outputs and writes Markdown about them. Install release 0.25.1 the same way, from its GitHub release and checksum file:

Bash
ARCH=$(dpkg --print-architecture)
TFD_VERSION=0.25.1
cd "$(mktemp -d)"
curl -fsSLO "https://github.com/terraform-docs/terraform-docs/releases/download/v${TFD_VERSION}/terraform-docs-v${TFD_VERSION}-linux-${ARCH}.tar.gz"
curl -fsSLO "https://github.com/terraform-docs/terraform-docs/releases/download/v${TFD_VERSION}/terraform-docs-v${TFD_VERSION}.sha256sum"
sha256sum --ignore-missing -c "terraform-docs-v${TFD_VERSION}.sha256sum"
tar -xzf "terraform-docs-v${TFD_VERSION}-linux-${ARCH}.tar.gz" terraform-docs
sudo install -m 0755 terraform-docs /usr/local/bin/terraform-docs
terraform-docs --version
git --version

Neither binary gets updates from apt. To upgrade, run the same commands with a newer TF_VERSION or TFD_VERSION.

Check it worked

Both sha256sum lines end in OK. terraform version prints Terraform v1.17.2 first, terraform-docs --version prints something like terraform-docs version v0.25.1 linux/amd64, and git --version prints a version number.

Step 2 · Lay out the module repository

Create the module in its own folder. Each file has one job, which is the layout the registry and most module tooling expect:

  • versions.tf says which Terraform versions the module supports
  • variables.tf holds the inputs, outputs.tf the outputs, main.tf the logic
  • examples/basic/ is a small root configuration that calls the module, so readers and CI can run it
  • README.md and CHANGELOG.md are for the humans who call it
Bash
mkdir -p ~/modules-demo/terraform-naming/examples/basic
cd ~/modules-demo/terraform-naming

cat > versions.tf <<'HCL'
terraform {
  # A shared module states a minimum, so it never blocks callers from upgrading.
  required_version = ">= 1.5.0"
}
HCL

cat > variables.tf <<'HCL'
variable "project" {
  type        = string
  description = "Short project name, used first in every name. Lowercase letters, digits and hyphens."

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{1,19}$", var.project))
    error_message = "project must be 2-20 characters: lowercase letters, digits and hyphens, starting with a letter."
  }
}

variable "environment" {
  type        = string
  description = "Deployment environment: dev, staging or prod."

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be one of dev, staging or prod."
  }
}

variable "extra_tags" {
  type        = map(string)
  description = "Additional tags merged over the standard ones."
  default     = {}
}
HCL

cat > main.tf <<'HCL'
locals {
  name_prefix = "${var.project}-${var.environment}"

  tags = merge(
    {
      Project     = var.project
      Environment = var.environment
      ManagedBy   = "terraform"
    },
    var.extra_tags,
  )
}
HCL

cat > outputs.tf <<'HCL'
output "name_prefix" {
  description = "Prefix for resource names, such as billing-prod."
  value       = local.name_prefix
}

output "tags" {
  description = "Standard tags to apply to every resource."
  value       = local.tags
}
HCL

cat > examples/basic/main.tf <<'HCL'
module "naming" {
  source = "../.."

  project     = "shop"
  environment = "dev"
  extra_tags = {
    CostCentre = "cc-104"
  }
}

output "name_prefix" {
  value = module.naming.name_prefix
}

output "tags" {
  value = module.naming.tags
}
HCL

cat > .gitignore <<'TXT'
.terraform/
.terraform.lock.hcl
*.tfstate
*.tfstate.*
TXT

The module ignores .terraform.lock.hcl on purpose. A lock file belongs to a root configuration that applies changes, not to a shared module: each caller keeps its own.

Format everything, then prove the module works by running its example:

Bash
cd ~/modules-demo/terraform-naming
terraform fmt -recursive
terraform -chdir=examples/basic init
terraform -chdir=examples/basic validate
terraform -chdir=examples/basic plan

Check it worked

init prints Initializing modules... and Terraform has been successfully initialized!. validate prints Success! The configuration is valid. The plan shows no resources, only Changes to Outputs: with name_prefix = "shop-dev" and a tags map that includes CostCentre = "cc-104" and ManagedBy = "terraform".

Step 3 · Generate the README inputs table with terraform-docs

A hand-written inputs table goes stale the first time someone adds a variable. Write the parts only a person can write, and leave two marker comments where terraform-docs should put the generated tables:

Bash
cd ~/modules-demo/terraform-naming

cat > README.md <<'MD'
# terraform-naming

Builds a consistent name prefix and tag map for every resource in a project.

## Usage

```hcl
module "naming" {
  source = "git::https://github.com/your-org/terraform-naming.git?ref=v1.0.0"

  project     = "billing"
  environment = "prod"
}
```

See `examples/basic` for a runnable example.

<!-- BEGIN_TF_DOCS -->
<!-- END_TF_DOCS -->
MD

cat > CHANGELOG.md <<'MD'
# Changelog

## 1.0.0

- First release: `name_prefix` and `tags` outputs.
MD

terraform-docs markdown table --output-file README.md .
cat README.md

--output-file in its default inject mode replaces only what sits between <!-- BEGIN_TF_DOCS --> and <!-- END_TF_DOCS -->, so your own text above stays as you wrote it. The your-org URL in the usage block is the address callers will use once the repository lives on your Git host; replace it with yours.

In CI, --output-check makes the same command fail when the README no longer matches the code, which stops anyone merging a new variable without its documentation.

Check it worked

README.md now has ## Requirements (showing terraform >= 1.5.0), ## Inputs and ## Outputs sections between the markers. The inputs table starts with the header | Name | Description | Type | Default | Required | and lists environment and project as required and extra_tags with a default of {}.

Step 4 · Tag v1.0.0 and push it to the shared repository

Create the shared repository. On GitHub or GitLab you would click "New repository"; here a bare repository, which stores history but has no working files, does the same job:

Bash
mkdir -p ~/modules-demo/remote
git init -q --bare -b main ~/modules-demo/remote/terraform-naming.git

Commit the module with a throwaway local identity (replace the name and email if you like), tag it, and push the branch and the tag:

Bash
cd ~/modules-demo/terraform-naming
git init -q -b main
git config user.name "Modules Demo"
git config user.email "modules-demo@example.com"
git add .
git commit -q -m "terraform-naming: first release"
git tag -a v1.0.0 -m "v1.0.0: name_prefix and tags outputs"
git remote add origin ~/modules-demo/remote/terraform-naming.git
git push -q -u origin main
git push -q origin v1.0.0
git ls-remote --tags origin

git push does not send tags unless you name them, which is why the tag gets its own push. Use annotated tags (-a): they record who tagged, when and why, and they are what git describe and most release tooling read.

Treat a pushed tag as permanent. Moving it with git tag -f means two callers pinned to the same v1.0.0 can hold different code, because Terraform keeps a copy of each module under .terraform/modules and does not fetch it again until init has a reason to. If a release is wrong, release v1.0.1.

Where a registry fits

A Git tag is enough for any team that can read the repository. A registry adds a module list, search and version = "~> 1.0" constraints, which Terraform does not support for Git sources:

  • The public Terraform Registry publishes modules from public GitHub repositories named terraform-<PROVIDER>-<NAME>, such as terraform-aws-naming, and picks up tags like v1.0.0 automatically. The layout you just built is the layout it expects.
  • The HCP Terraform private registry and GitLab's Terraform module registry do the same for private code, each with its own source address format.

None of them is needed for this tutorial, and the tags you create work with all of them.

Check it worked

git ls-remote --tags origin prints two lines: one ending refs/tags/v1.0.0 and one ending refs/tags/v1.0.0^{}. The second is the commit the annotated tag points at.

Step 5 · Use the module from another project with a git:: source

Create the project that consumes the module. The git:: prefix tells Terraform to clone with Git, and ?ref=v1.0.0 picks the tag:

Bash
mkdir -p ~/modules-demo/billing-app
cd ~/modules-demo/billing-app

cat > main.tf <<HCL
module "naming" {
  source = "git::file://${HOME}/modules-demo/remote/terraform-naming.git?ref=v1.0.0"

  project     = "billing"
  environment = "prod"
}

output "name_prefix" {
  value = module.naming.name_prefix
}

output "tags" {
  value = module.naming.tags
}
HCL

grep source main.tf
terraform init
terraform plan -out=tfplan
terraform apply tfplan

The heredoc is unquoted this time so the shell writes your real home folder into the file:// URL. Against a hosted repository, the source line looks like one of these, over HTTPS or SSH:

HCL
source = "git::https://github.com/your-org/terraform-naming.git?ref=v1.0.0"
source = "git::ssh://git@github.com/your-org/terraform-naming.git?ref=v1.0.0"

Two options are worth knowing:

  • ?ref= also accepts a full commit SHA. A SHA cannot be moved the way a tag can, so some teams pin to the SHA and keep the tag in a comment.
  • &depth=1 after the ref makes a shallow clone of just that tag. On a large module repository and a prepaid or metered connection, that can save a lot of data on every fresh init.

Check it worked

init prints a line like Downloading git::file:///home/you/modules-demo/remote/terraform-naming.git?ref=v1.0.0 for naming.... The apply ends with Apply complete! Resources: 0 added, 0 changed, 0 destroyed. and prints name_prefix = "billing-prod" and the three standard tags. cat .terraform/modules/modules.json shows the naming module recorded with ref=v1.0.0.

Step 6 · Make a breaking change and release v2.0.0

Your platform team now wants every resource to carry an owner, so the module gains a required owner input. Adding a required input is a breaking change: every existing caller fails until it passes one. Other breaking changes include renaming or removing a variable or output, changing a type, raising required_version, and changing resource addresses without moved blocks. Each of those needs a major version.

Rewrite the two files that change. variables.tf is rewritten whole, with the new variable added at the end:

Bash
cd ~/modules-demo/terraform-naming

cat > variables.tf <<'HCL'
variable "project" {
  type        = string
  description = "Short project name, used first in every name. Lowercase letters, digits and hyphens."

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{1,19}$", var.project))
    error_message = "project must be 2-20 characters: lowercase letters, digits and hyphens, starting with a letter."
  }
}

variable "environment" {
  type        = string
  description = "Deployment environment: dev, staging or prod."

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be one of dev, staging or prod."
  }
}

variable "extra_tags" {
  type        = map(string)
  description = "Additional tags merged over the standard ones."
  default     = {}
}

variable "owner" {
  type        = string
  description = "Team or contact responsible for the resources, such as a team email address."

  validation {
    condition     = length(trimspace(var.owner)) > 0
    error_message = "owner must not be empty."
  }
}
HCL

cat > main.tf <<'HCL'
locals {
  name_prefix = "${var.project}-${var.environment}"

  tags = merge(
    {
      Project     = var.project
      Environment = var.environment
      Owner       = var.owner
      ManagedBy   = "terraform"
    },
    var.extra_tags,
  )
}
HCL

Before regenerating anything, ask terraform-docs whether the README still matches the code:

Bash
terraform-docs markdown table --output-file README.md --output-check .

It fails, saying something like README.md is out of date, because owner is not in the table yet. That is the check you would run in CI.

Now bring everything else up to date: the example passes an owner, the README is regenerated, and the changelog tells callers exactly what to do:

Bash
cd ~/modules-demo/terraform-naming

cat > examples/basic/main.tf <<'HCL'
module "naming" {
  source = "../.."

  project     = "shop"
  environment = "dev"
  owner       = "shop-team@example.com"
  extra_tags = {
    CostCentre = "cc-104"
  }
}

output "name_prefix" {
  value = module.naming.name_prefix
}

output "tags" {
  value = module.naming.tags
}
HCL

cat > CHANGELOG.md <<'MD'
# Changelog

## 2.0.0

- Breaking: new required input `owner`, added to `tags` as `Owner`.
- Upgrading from 1.x: add `owner = "<team or email>"` to the module block, then run `terraform init` and `terraform plan`. No resources are replaced; only tag values change.

## 1.0.0

- First release: `name_prefix` and `tags` outputs.
MD

terraform fmt -recursive
terraform-docs markdown table --output-file README.md .
terraform -chdir=examples/basic validate
terraform -chdir=examples/basic plan

Commit, tag and push the release:

Bash
cd ~/modules-demo/terraform-naming
git add .
git commit -q -m "Require owner input (breaking)"
git tag -a v2.0.0 -m "v2.0.0: owner is required"
git push -q origin main
git push -q origin v2.0.0
git ls-remote --tags origin

The README's usage block still says ?ref=v1.0.0. Change it to v2.0.0 in your editor in the next release you make, or before tagging if you prefer; it is text for humans and Terraform never reads it.

Check it worked

Before regenerating, --output-check exits with an error. After it, the README's inputs table has an owner row marked required, and the example plan shows Owner = "shop-team@example.com" in tags. git ls-remote --tags origin now lists both refs/tags/v1.0.0 and refs/tags/v2.0.0, each with its ^{} line.

Step 7 · Upgrade the caller to v2.0.0 on purpose

First, confirm the release did not reach the caller on its own. Even init -upgrade, which re-fetches every module, stays on the tag written in the source:

Bash
cd ~/modules-demo/billing-app
terraform init -upgrade
terraform plan

Now upgrade deliberately. Read the module's changelog first, then change the ref:

Bash
git -C ~/modules-demo/terraform-naming show v2.0.0:CHANGELOG.md

cd ~/modules-demo/billing-app
cat > main.tf <<HCL
module "naming" {
  source = "git::file://${HOME}/modules-demo/remote/terraform-naming.git?ref=v2.0.0"

  project     = "billing"
  environment = "prod"
}

output "name_prefix" {
  value = module.naming.name_prefix
}

output "tags" {
  value = module.naming.tags
}
HCL

Try to plan before doing anything else, then install the new version and plan again:

Bash
terraform plan
terraform init
terraform plan

The first plan refuses to run, with an error saying the module source has changed and that you need to run terraform init. init then downloads ?ref=v2.0.0. The second plan fails too, this time on your code: Missing required argument with The argument "owner" is required, but no definition was found. That is the breaking change doing its job: you find out at plan time, in the project you chose to upgrade, not in every project at once.

Add the owner, as the changelog said, and apply:

Bash
cd ~/modules-demo/billing-app
cat > main.tf <<HCL
module "naming" {
  source = "git::file://${HOME}/modules-demo/remote/terraform-naming.git?ref=v2.0.0"

  project     = "billing"
  environment = "prod"
  owner       = "billing-team@example.com"
}

output "name_prefix" {
  value = module.naming.name_prefix
}

output "tags" {
  value = module.naming.tags
}
HCL

terraform init
terraform plan -out=tfplan
terraform apply tfplan

In a real project this change goes through a pull request: the diff is one line in source and one new argument, and the plan output in the review shows exactly which tags change.

Check it worked

The init -upgrade and plan at the start report no changes, and name_prefix stays billing-prod. After the upgrade, the plan shows tags changing with + Owner = "billing-team@example.com", and after the apply terraform output tags includes Owner. .terraform/modules/modules.json now records ref=v2.0.0.

Step 8 · Clean up

The caller holds only outputs in its state, so there is nothing real to destroy. The next command deletes the whole demo folder: the module, the shared repository and the caller. Check you are deleting ~/modules-demo and nothing else:

Bash
cd ~
rm -rf ~/modules-demo

If you installed the tools only for this tutorial, remove them too:

Bash
sudo rm -f /usr/local/bin/terraform /usr/local/bin/terraform-docs

Check it worked

ls ~/modules-demo reports No such file or directory, and command -v terraform-docs prints nothing if you removed the binaries.

Next steps

  • Run the same module from OpenTofu, which reads git:: sources identically, in /tutorials/manage-infrastructure-with-opentofu.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.