In the previous lesson you drew the blueprint: network, data and app, with the resource-by-resource allocation and the minimal outputs of each one. Today you go down to the workshop and write a whole one. You are going to build EcoMarket's network module from start to finish — its interface, its implementation, its templates, its documentation and its runnable example — and you will finish by extracting the real resources from the monolith into that module with moved blocks, checking that the plan comes out at 0 to add, 0 to change, 0 to destroy. A complete refactor without destroying anything: exactly the promise you brought with you from module 3.
- Designing the interface before the implementation
There is an enormous temptation when creating a module: take the block of resources that already works, move it to a new directory and turn everything that was in var. or local. into a variable. It is quick and it produces bad modules, because the interface ends up being an accident of how the monolith happened to be written rather than a decision.
The right order is the reverse. First you write how you want the module to be used, and then you implement it so that call works. Write literally this on paper or in the README.md before touching main.tf:
# This is how I want EcoMarket's network module to be called.
module "network" {
source = "./modules/network"
base_name = local.prefix # "ecomarket-dev"
cidr = "10.20.0.0/16"
zones = ["eu-west-1a", "eu-west-1b"]
tags = local.common_tags
}Four inputs. That is the acid test: if the ideal call fits in five lines and is understandable without reading documentation, the boundary is in the right place. If writing it takes twenty arguments, go back to the five-question rule from the previous lesson.
With the call written, classify every aspect of the module into one of three boxes:
| Box | Meaning | Example in network |
|---|---|---|
| Exposed | The consumer must decide it; it varies between environments or projects | cidr, zones, base_name, tags |
| Exposed with a default | They can decide it, but there is a sensible answer | create_nat, subnet_bits, enable_dns |
| Fixed inside the module | It is policy, not configuration; nobody should be able to change it | Flow logs switched on, the <base>-vpc naming, the minimum subnet size |
The third box is what gives the module its value. If everything is configurable, you have encapsulated nothing: you have written the provider-mirror antipattern. A good module has opinions. And the question that settles any doubt is always the same: does it make sense for dev and prod to differ on this? If the answer is no, it goes fixed inside.
Seen as a data flow, a module has this shape, and the three boxes sit in different places:
flowchart LR
C["Consumer<br/>module "network" { ... }"] -->|"exposed"| V
subgraph M["modules/network/ — the module boundary"]
V["variables.tf<br/><i>base_name, cidr, zones,<br/>create_nat, tags</i>"] --> L
F["FIXED INSIDE<br/><i>flow logs, naming,<br/>base rules</i>"] --> L
L["locals.tf<br/><i>vpc_name, tags,<br/>subnet map</i>"] --> R
P["templates/<br/><i>path.module</i>"] --> R
R["main.tf<br/><i>local_file.vpc<br/>local_file.subnet</i>"] --> O["outputs.tf<br/><i>vpc_id, private_subnets,<br/>network (object)</i>"]
end
O -->|"module.network.vpc_id"| C
style V fill:#e8f0fe,stroke:#1a73e8
style O fill:#e9f7ef,stroke:#2f855a
style F fill:#ffe5e5,stroke:#c53030
Only the two coloured boxes cross the boundary. Everything else — the locals, the templates, the resource names, the fixed decisions — is private, and that is why it can be changed without publishing a major version… with the single exception of the resource names, which are state addresses. We will come back to that exception in section 10 and, in depth, in 04-05.
There is an important asymmetry worth knowing before you decide:
- Widening the interface is cheap. Adding a variable with a
defaultis a minor change: nobody breaks. - Narrowing it is expensive. Removing or renaming a variable breaks every consumer and forces a major version.
So, when in doubt, do not expose. You can always expose it later when somebody asks, and then you will also know what they want it for.
variables.tf: the input contract
variables.tf: the input contractWith the design settled, this is the network module's variables.tf:
# modules/network/variables.tf
variable "base_name" {
description = "Prefix used to name every network resource. Usually '<project>-<environment>'."
type = string
nullable = false
validation {
condition = can(regex("^[a-z][a-z0-9-]{2,30}$", var.base_name))
error_message = "base_name must start with a lower-case letter and contain only lower-case letters, digits and hyphens (3-31 characters). Received: '${var.base_name}'."
}
}
variable "cidr" {
description = "CIDR block of the VPC. Must be a private /16 to /20."
type = string
nullable = false
validation {
condition = can(cidrnetmask(var.cidr))
error_message = "cidr is not a valid CIDR block. Valid example: '10.20.0.0/16'."
}
validation {
condition = tonumber(split("/", var.cidr)[1]) >= 16 && tonumber(split("/", var.cidr)[1]) <= 20
error_message = "The cidr prefix must be between /16 and /20 so that the per-zone subnets fit."
}
}
variable "zones" {
description = "Availability zones in which to create subnets. One private subnet per zone."
type = list(string)
nullable = false
validation {
condition = length(var.zones) >= 1 && length(var.zones) <= 4
error_message = "Between 1 and 4 zones are accepted. Received: ${length(var.zones)}."
}
validation {
condition = length(var.zones) == length(distinct(var.zones))
error_message = "There are repeated zones in the list: ${join(", ", var.zones)}."
}
}
variable "subnet_bits" {
description = "Extra bits added to the VPC prefix to compute each subnet. With a /16 and 8 bits you get /24 subnets."
type = number
default = 8
validation {
condition = var.subnet_bits >= 4 && var.subnet_bits <= 12
error_message = "subnet_bits must be between 4 and 12."
}
}
variable "create_nat" {
description = "Create a NAT gateway to give the private subnets internet egress. Worth switching off in dev for cost."
type = bool
default = true
}
variable "tags" {
description = "Tags applied to every resource in the module. They are merged with the ones the module adds on its own."
type = map(string)
default = {}
nullable = false
}Six variables for an entire network module. Let us go through the decisions behind them, because every one of them applies to any module you write.
nullable = false and why it matters. By default a variable accepts null, and passing null explicitly makes Terraform use the default. That is fine for optional variables, but dangerous on mandatory ones: base_name = null would produce names like -vpc with no error at all. With nullable = false, Terraform rejects the null with a clear message. Rule: nullable = false on everything mandatory and on maps and lists with default = {} or [], so that nobody can null them out and trigger an error a hundred lines away.
Several validation blocks on the same variable. Since Terraform 1.x you can stack them, and it is far better than one giant condition joined with &&, because each one carries its own message. Compare what the consumer gets:
# With a single combined validation: Error: cidr is not valid. # With two separate validations: Error: The cidr prefix must be between /16 and /20 so that the per-zone subnets fit.
The second message fixes itself; the first one generates a message on Slack. In a shared module, the error message is part of the documentation: it is going to be read by somebody who has never seen your code.
Interpolating the received value into the message. Received: '${var.base_name}' saves a round of questions. You can only reference the variable itself inside its own validation, not others.
Defaults that serve the common case, not the cheap case. create_nat = true by default, and whoever wants to save money in dev switches it off explicitly. The general criterion: the default value must be the safe and correct one, not the cheapest or the most permissive. If somebody deploys the module without reading anything, what they get must be valid for production.
What this interface deliberately does NOT have, which is as important as what it does:
| Not exposed | Why |
|---|---|
environment |
The module does not need to know which environment it is in; base_name and tags are enough. A module that branches on var.environment == "prod" is a module that cannot be reused in another project with different environment names. |
region |
The region comes from the provider configuration, which the parent injects. Duplicating it as a variable creates the possibility that the two disagree. |
| Individual names for each subnet | They are derived from base_name; exposing them would allow inconsistent names. |
enable_flow_logs |
It is security policy: always on. If a real case tomorrow demands switching them off, the variable gets added then. |
That first case deserves emphasis because it is the most frequent design mistake in internal modules: passing var.environment into the module and branching inside with conditionals. It turns the module into a catalogue of your company's special cases, impossible to reuse and to test. The right approach is for the parent to translate "environment" into concrete parameters — create_nat = local.current.create_nat — and for the module to see only the parameters.
outputs.tf: the output contract
outputs.tf: the output contractOutputs are the other half of the contract and they tend to be written with less care, which is a mistake: renaming an output breaks consumers just as much as renaming a variable.
# modules/network/outputs.tf
output "vpc_id" {
description = "Identifier of the created VPC. Needed for security groups and extra subnets."
value = local_file.vpc.id
}
output "vpc_name" {
description = "Logical name of the VPC, derived from base_name."
value = local.vpc_name
}
output "cidr" {
description = "Effective CIDR block of the VPC, useful for other modules' ingress rules."
value = var.cidr
}
output "private_subnets" {
description = "Map from availability zone to private subnet identifier."
value = { for z, s in local_file.subnet : z => s.id }
}
output "subnet_ids" {
description = "Flat list of subnet identifiers, for resources that expect a list."
value = [for z in var.zones : local_file.subnet[z].id]
}
output "network" {
description = "Composite object with everything a typical consumer needs. Preferable to consuming the individual outputs."
value = {
vpc_id = local_file.vpc.id
vpc_name = local.vpc_name
cidr = var.cidr
private_subnets = { for z, s in local_file.subnet : z => s.id }
zones = var.zones
}
}Three categories of output, and it is worth being clear about them:
| Category | Example | When to use it |
|---|---|---|
| Identifiers | vpc_id, private_subnets |
Always. It is what other modules need in order to refer to what you created |
| Derived values | vpc_name, cidr |
When the consumer would otherwise have to recompute them and could get it wrong |
| Composite objects | network |
When the typical consumer needs several things at once |
The composite object deserves an explicit defence. Compare these two calls:
# Without a composite object: four threads to maintain
module "app" {
source = "./modules/app"
vpc_id = module.network.vpc_id
subnets = module.network.private_subnets
network_cidr = module.network.cidr
zones = module.network.zones
}
# With a composite object: one thread
module "app" {
source = "./modules/app"
network = module.network.network
}The second version has a decisive advantage: adding a new field to network does not force any consumer to change. With individual outputs, every new piece of data that app needs means changing the call in three environments. The cost is that the coupling between network and app becomes implicit: app receives an object and only the documentation says which fields it expects. The practical recommendation: publish both, the individual ones for consumers that need a single piece and the composite object for the natural consumer. Outputs cost nothing at runtime.
sensitive on module outputs and the classic error
An output containing a secret is marked the same way as in the root module:
# modules/data/outputs.tf
output "connection_string" {
description = "Full PostgreSQL connection string, password included."
value = "postgresql://${var.db_user}:${var.db_password}@${local.db_host}:5432/ecomarket"
sensitive = true
}And here comes the error you will hit as soon as you try to republish it from the parent:
╷
│ Error: Output refers to sensitive values
│
│ on outputs.tf line 1:
│ 1: output "connection" {
│
│ To reduce the risk of accidentally exporting sensitive data that was
│ intended to be only internal, Terraform requires that any root module
│ output containing sensitive data be explicitly marked as sensitive, to
│ confirm your intent.
╵Sensitivity propagates. The moment a sensitive value enters an expression, the whole result is tainted, and that is desirable: it stops a secret leaking out carelessly inside an interpolation. The fix is to declare the intent:
Three clarifications that avoid nasty surprises:
sensitivehides the value inplanandapplyoutput, not in state. It is still in the clear in thetfstate, just as you saw in Understanding State. It is protection against shoulder-surfing and against pipeline logs, not encryption.- A sensitive output taints everything it touches. If you put it inside the
networkcomposite object, the entire object becomes sensitive and you will stop seeingvpc_idin theplan. Never mix secrets with ordinary data in a composite object. nonsensitive()exists, and you should use it with extreme care. It removes the marking from a value. It is justified when the sensitivity is a false positive — for example, a map key derived from a sensitive value that reveals nothing — and it is a bad idea in every other case.
versions.tf: why a module does not configure providers
versions.tf: why a module does not configure providers# modules/network/versions.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
local = {
source = "hashicorp/local"
version = ">= 2.4.0"
}
random = {
source = "hashicorp/random"
version = ">= 3.5.0"
}
}
}
# There is NO "provider" block here. And that is deliberate.We pick up the rule you stated in Providers: provider blocks live only in the root module. Now it is time to understand why, because there are four reasons and all of them are practical:
-
The consumer must decide where it is deployed. If the
networkmodule pinnedprovider "aws" { region = "eu-west-1" }, it would be impossible to use it inus-east-1. The region, the credentials and the assumed role are the consumer's decisions, not the module's. -
Providers cannot be "unconfigured". A module with a
providerinside imposes its configuration on everything below it, and the parent has no way to override it. -
Terraform forbids it in practice. A module with its own
providerblock is a legacy module: it cannot be used withcount,for_eachordepends_on. The error is explicit:│ Error: Module is incompatible with count, for_each, and depends_on │ │ The module at module.network 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. -
Destruction breaks. If the module disappears from the configuration, the provider configuration Terraform needs in order to destroy its resources disappears with it, and you are left with a state you cannot clean up.
The correct model: the module declares which providers it needs and with what version constraints, and the parent injects the configurations. Inheritance is automatic for the default instance:
# infra/app/versions.tf — the ROOT does configure
terraform {
required_version = ">= 1.5.0"
required_providers {
local = { source = "hashicorp/local", version = "~> 2.5" }
}
}
provider "local" {} # configured once, here
module "network" {
source = "../../modules/network"
# Nothing about providers is passed: it inherits the default instance.
}A note on version constraints in a shared module, which differ from the ones you use in a root:
| Reusable module | Root configuration | |
|---|---|---|
| Typical constraint | >= 2.4.0 |
~> 2.5.1 |
| Reason | Pinning too tightly stops the consumer combining several modules | The root decides the exact version and pins it in .terraform.lock.hcl |
required_version |
A minimum (>= 1.5.0) |
A minimum, plus .terraform-version for the team |
The reason is dependency resolution: Terraform has to find one single version of each provider that satisfies every module at once. If network demands ~> 5.1.0 and data demands ~> 5.3.0, there is no solution and init fails. With broad minimums there always is one. And the exact pin is set by the root in its .terraform.lock.hcl, which is where it belongs.
configuration_aliases: when the module needs two instances
configuration_aliases: when the module needs two instancesSometimes a module needs two configurations of the same provider. EcoMarket's real case: the images bucket has a replica in eu-central-1 for disaster recovery, so the data module has to create resources in two regions.
The module cannot declare those instances — we have just seen why — but it can declare that it expects them:
# modules/data/versions.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
local = {
source = "hashicorp/local"
version = ">= 2.4.0"
configuration_aliases = [local.main, local.replica]
}
random = {
source = "hashicorp/random"
version = ">= 3.5.0"
}
}
}Inside the module, each resource picks its instance:
# modules/data/main.tf
resource "local_file" "images_bucket" {
provider = local.main
filename = "${path.root}/output/${var.base_name}-images.json"
content = jsonencode({ region = "eu-west-1", versioning = true })
}
resource "local_file" "replica_bucket" {
provider = local.replica
filename = "${path.root}/output/${var.base_name}-images-replica.json"
content = jsonencode({ region = "eu-central-1", source = local_file.images_bucket.filename })
}And the parent is obliged to pass them, with providers:
# infra/app/main.tf
provider "local" {} # default instance
provider "local" {
alias = "dr" # second instance
}
module "data" {
source = "../../modules/data"
providers = {
local.main = local # left: what the MODULE expects
local.replica = local.dr # right: what the PARENT has
}
base_name = local.prefix
}Three rules that save hours:
- To the left of the
=goes the module's internal name; to the right, the parent's. It gets confused constantly. A useful reading: "the module'slocal.mainis filled in with mylocal". - Declaring a
configuration_aliasmakes it mandatory. If the parent does not pass it,initfails withprovider configuration not present. That is a good thing: there is no way to forget it silently. - If the module declares
configuration_aliases, automatic inheritance stops being enough for that provider. You have to be explicit about every instance the module uses.
- Paths inside a module:
path.module, path.root and path.cwd
path.module, path.root and path.cwdThis section settles a bug that everybody writes once. Terraform offers three path expressions and inside a module they are not the same:
| Expression | What it points at | Value inside modules/network/ called from infra/app/ |
What it is for |
|---|---|---|---|
path.module |
Directory of the module containing the expression | ../../modules/network |
Reading files that travel with the module: templates, policies, scripts |
path.root |
Directory of the root module (where terraform runs) |
. |
Writing outputs relative to the consumer's project |
path.cwd |
The process's working directory | Normally .; different with -chdir |
Almost never; only with -chdir and knowing what you are doing |
The distinction is easy to remember if you think of it like this: path.module is "my stuff", path.root is "the stuff of whoever called me".
The classic mistake:
# INSIDE modules/network/main.tf — WRONG
resource "local_file" "policy" {
content = file("${path.root}/templates/policy.json")
filename = "output/policy.json"
}It works on your machine while the module is local and the template happens to be in the root. The moment you publish the module to Git and somebody consumes it from another repository:
╷
│ Error: Invalid function argument
│
│ on ../../modules/network/main.tf line 2, in resource "local_file" "policy":
│ 2: content = file("${path.root}/templates/policy.json")
│
│ Invalid value for "path" parameter: no file exists at
│ "./templates/policy.json".
╵The template travels inside the module, so the path must be relative to the module:
# RIGHT
resource "local_file" "policy" {
content = file("${path.module}/templates/policy.json")
filename = "${path.root}/output/policy.json"
}Notice that both appear in the same resource and each does its own job: you read from path.module (a file belonging to the module) and you write to path.root (the consumer's project output). Writing into path.module would be dirtying the module's directory, which may in addition be a read-only cache inside .terraform/modules/.
- Static files and templates inside the module
A module can — and usually does — carry files that are not .tf. Two functions consume them:
# The file as-is, no substitutions
content = file("${path.module}/templates/base-policy.json")
# A template with substitutions
content = templatefile("${path.module}/templates/vpc.json.tftpl", {
name = local.vpc_name
cidr = var.cidr
zones = var.zones
tags = local.tags
})The template, with the conventional .tftpl extension:
# modules/network/templates/vpc.json.tftpl
{
"name": "${name}",
"cidr": "${cidr}",
"dns": { "hostnames": true, "resolution": true },
"subnets": [
%{ for i, z in zones ~}
{ "zone": "${z}", "cidr": "${cidrsubnet(cidr, 8, i)}" }%{ if i < length(zones) - 1 },%{ endif }
%{ endfor ~}
],
"tags": ${jsonencode(tags)}
}Four details about templatefile worth nailing down:
- Only the variables you pass in the second argument exist. Inside the template there is no
var., nolocal., and no references to resources. It is a closed environment, and that is a good thing: the template is a pure function of its inputs. - The
%{ for }and%{ if }directives are the ones from module 2, and the tilde~trims the adjacent whitespace, which does not matter in JSON but very much does in an indented configuration file. - To insert a structure, use
jsonencode(). Trying to build JSON by hand with loops produces one comma too many or too few; it is the number one cause of broken templates. - The
.tftplextension is not mandatory but it is the convention, and it stops editors trying to validate the file as JSON while it still has markers in it.
When a template is worth it compared with jsonencode() in HCL. If you are generating pure JSON or YAML, jsonencode()/yamlencode() from HCL is safer: you cannot produce invalid syntax. The template wins when the format is not JSON (an nginx.conf, a boot script, an .ini file) or when the result has to be readable by a human, with comments and a specific ordering.
- Internal
locals: the module's back room
locals: the module's back roomA module's locals are private: they cannot be passed in from outside nor read from outside. That privacy is exactly what you need in order not to clutter the interface.
# modules/network/locals.tf
locals {
# Derived names: a single definition of the convention.
vpc_name = "${var.base_name}-vpc"
# Effective tags: the consumer's plus the ones the module contributes.
tags = merge(
var.tags,
{
Module = "network"
ModuleVersion = local.module_version
},
)
# Version of the module itself, so you can audit which version created each resource.
module_version = "2.1.0"
# Subnet computation: each zone gets a consecutive block.
# cidrsubnet("10.20.0.0/16", 8, 0) -> "10.20.0.0/24"
# cidrsubnet("10.20.0.0/16", 8, 1) -> "10.20.1.0/24"
subnets = {
for i, zone in var.zones :
zone => {
index = i
cidr = cidrsubnet(var.cidr, var.subnet_bits, i)
name = "${var.base_name}-priv-${zone}"
}
}
}That locals.subnets is the most useful pattern in the whole section and it is worth developing. Compute first, create afterwards. Instead of putting the logic inside the resource's for_each, you build a map with everything already resolved and the resource becomes trivial:
resource "local_file" "subnet" {
for_each = local.subnets
filename = "${path.root}/output/${each.value.name}.json"
content = jsonencode({
name = each.value.name
zone = each.key
cidr = each.value.cidr
vpc = local.vpc_name
})
}Three concrete advantages:
- It can be inspected without applying anything. Open
terraform consoleand evaluatelocal.subnetsto see the whole map before planning. - The
for_eachkeys are stable: they are the zones, not indices. You already know from Resource and Data Blocks what happens with indices when an element in the middle is removed. - The logic is in one place, not scattered between
for_each,filenameandcontent.
A warning about local.module_version: it is a hand-written string that you have to remember to update on every release. Terraform does not expose the running module's version, so there is no automatic alternative from inside. It is worth it because it lets you audit which resources come from an old version, but it is one more line on the release checklist you will see in 04-05.
- Tagging: accept, merge and do not impose
Tagging is the most repeated design decision in infrastructure modules and it has a canonical solution: the module accepts a map, merges it with its own and applies it to everything.
locals {
tags = merge(
var.tags, # 1. what comes from the consumer
{ # 2. what the module adds (and which wins)
Module = "network"
ModuleVersion = local.module_version
},
)
}The order of merge() is a decision, not a detail: the right-hand side wins. Here the module reserves Module and ModuleVersion so that a consumer cannot falsify them. If you wanted the opposite — the consumer able to override everything — you would reverse the order.
A comparison of the three strategies you see in practice:
| Strategy | Implementation | Advantage | Drawback |
|---|---|---|---|
| The module does not tag | There is no var.tags; the consumer can do nothing |
Simpler module | Useless: no company accepts untagged resources |
| The module accepts and merges (recommended) | var.tags + merge() in a local |
Flexible, auditable, works in any organisation | You have to remember to put tags = local.tags on every resource |
The provider's default_tags |
Configured in the root's provider block |
Zero code in the module, applied to everything automatically | Only some providers have it (AWS does); it does not cover tags that depend on the module; it can produce drift with tags managed elsewhere |
The recommendation for EcoMarket is the second, and it is also compatible with the third: default_tags on the provider for Project, Environment and ManagedBy, and var.tags in the module for the specific ones. They do not get in each other's way.
- Naming conventions inside the module
Inside a module, the resource name already carries context: the full address will be module.network.<type>.<name>. Repeating "network" inside is redundant.
# Inside modules/network/ — REDUNDANT
resource "aws_vpc" "ecomarket_network_vpc" {} # module.network.aws_vpc.ecomarket_network_vpc
# Inside modules/network/ — GOOD
resource "aws_vpc" "this" {} # module.network.aws_vpc.this
resource "aws_vpc" "main" {} # module.network.aws_vpc.mainThe most widespread convention in the community — and the one the terraform-aws-modules modules use — is to call the module's principal resource this, the one that gives the module its name and of which there is only one. In this course we use main because it reads more plainly in prose; both are correct and what matters is being consistent.
| Situation | Recommended name | Resulting address |
|---|---|---|
| The principal, single resource | this or main |
module.network.aws_vpc.main |
| Several instances of the same type | The name of the role | module.network.aws_subnet.private["eu-west-1a"] |
| Helper resources of the principal one | The name of the function | module.network.aws_route_table.private |
| Conditional resource | Name + intent | module.network.aws_nat_gateway.egress[0] |
And a rule worth its weight in gold: do not change these names lightly. They are state addresses. Renaming main to this in version 2.1.0 of your module destroys the VPC of every consumer that upgrades… unless you include a moved block inside the module, which is precisely the compatibility contract you will see in 04-05.
- The complete
network module
network moduleAll the pieces together. This runs with the local and random providers, with no cloud account:
# modules/network/main.tf
resource "local_file" "vpc" {
filename = "${path.root}/output/${local.vpc_name}.json"
content = templatefile("${path.module}/templates/vpc.json.tftpl", {
name = local.vpc_name
cidr = var.cidr
zones = var.zones
tags = local.tags
})
}
resource "local_file" "subnet" {
for_each = local.subnets
filename = "${path.root}/output/${each.value.name}.json"
content = jsonencode({
name = each.value.name
zone = each.key
cidr = each.value.cidr
vpc = local.vpc_name
public = false
tags = merge(local.tags, { Tier = "private", AZ = each.key })
})
}
# NAT gateway: conditional, with count as a switch (the 02-03 pattern).
resource "local_file" "nat" {
count = var.create_nat ? 1 : 0
filename = "${path.root}/output/${var.base_name}-nat.json"
content = jsonencode({
name = "${var.base_name}-nat"
zone = var.zones[0]
tags = local.tags
})
}
# Base security group: module policy, not configurable from outside.
resource "local_file" "base_security_group" {
filename = "${path.root}/output/${var.base_name}-sg-base.json"
content = jsonencode({
name = "${var.base_name}-sg-base"
vpc = local.vpc_name
ingress_rules = [
{ protocol = "tcp", port = 443, source = var.cidr, description = "Internal HTTPS" },
]
egress_rules = [
{ protocol = "-1", port = 0, destination = "0.0.0.0/0", description = "Unrestricted egress" },
]
tags = local.tags
})
}And the realistic AWS equivalent, for reference, not runnable here — the real cloud deployment arrives in module 5:
# modules/network/main.tf — AWS version (reference)
# resource "aws_vpc" "main" {
# cidr_block = var.cidr
# enable_dns_hostnames = true
# enable_dns_support = true
# tags = merge(local.tags, { Name = local.vpc_name })
# }
#
# resource "aws_subnet" "private" {
# for_each = local.subnets
#
# vpc_id = aws_vpc.main.id
# cidr_block = each.value.cidr
# availability_zone = each.key
# tags = merge(local.tags, { Name = each.value.name, Tier = "private" })
# }
#
# resource "aws_nat_gateway" "egress" {
# count = var.create_nat ? 1 : 0
# allocation_id = aws_eip.nat[0].id
# subnet_id = aws_subnet.public[var.zones[0]].id
# tags = merge(local.tags, { Name = "${var.base_name}-nat" })
# }The structure, the interface and the locals are identical in both versions. That is intentional: what you are learning is not how to write local files, it is the shape of a module, and it carries over unchanged to AWS, Azure or GCP.
Final tree of the module:
modules/network/
├── main.tf
├── locals.tf
├── variables.tf
├── outputs.tf
├── versions.tf
├── README.md
├── CHANGELOG.md
├── templates/
│ └── vpc.json.tftpl
├── examples/
│ └── complete/
│ ├── main.tf
│ ├── versions.tf
│ └── outputs.tf
└── tests/
└── basic.tftest.hcl
README.md and terraform-docs
README.md and terraform-docsA module's README.md has a conventional structure that is worth respecting because it is the one the registry expects and the one people look for:
# modules/network
Creates EcoMarket's base network: a VPC, one private subnet per availability
zone, an optional NAT gateway and a base security group that allows
internal HTTPS.
## Usage
```hcl
module "network" {
source = "git::https://github.com/ecomarket/terraform-aws-ecomarket-network.git?ref=v2.1.0"
base_name = "ecomarket-dev"
cidr = "10.20.0.0/16"
zones = ["eu-west-1a", "eu-west-1b"]
create_nat = false # dev saves the cost of the NAT
tags = { Project = "ecomarket", Environment = "dev" }
}
```
## Notes
- Flow logs are **always** on: it is security policy and it is not
configurable.
- `cidr` must be a block between /16 and /20.
- Contact: [email protected]
<!-- BEGIN_TF_DOCS -->
<!-- END_TF_DOCS -->Those two markers at the end are the key: terraform-docs automatically generates between them the tables of requirements, providers, inputs, outputs and resources, reading the description fields you wrote.
# Installation (Linux)
$ curl -sSLo terraform-docs.tar.gz \
https://terraform-docs.io/dl/v0.19.0/terraform-docs-v0.19.0-linux-amd64.tar.gz
$ tar -xzf terraform-docs.tar.gz terraform-docs && sudo mv terraform-docs /usr/local/bin/
# Print the documentation on screen
$ terraform-docs markdown table modules/network/
# Inject it into the README between the markers
$ terraform-docs markdown table --output-file README.md --output-mode inject modules/network/A configuration file reduces the command to a single one for the whole repository:
# .terraform-docs.yml
formatter: markdown table
output:
file: README.md
mode: inject
sort:
enabled: true
by: required # required ones first
settings:
anchor: false
default: true
required: true
type: trueAnd this is the fragment it generates for our module:
## Inputs
| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| base\_name | Prefix used to name every network resource. | `string` | n/a | yes |
| cidr | CIDR block of the VPC. Must be a private /16 to /20. | `string` | n/a | yes |
| zones | Availability zones in which to create subnets. | `list(string)` | n/a | yes |
| create\_nat | Create a NAT gateway for the private subnets. | `bool` | `true` | no |
| subnet\_bits | Extra bits used to compute each subnet. | `number` | `8` | no |
| tags | Tags applied to every resource in the module. | `map(string)` | `{}` | no |Two practical consequences of using terraform-docs:
- Each variable's
descriptionstops being optional. It is what gets published. A variable with no description comes out with an empty cell and it shows. - The documentation can be verified in CI.
terraform-docs --output-checkfails if the README is out of sync with the code, exactly liketerraform fmt -check. You will wire it up in module 8, but it is worth knowing from now that out-of-date documentation is a build failure, not an oversight.
examples/: documentation that runs
examples/: documentation that runsAn examples/ directory with complete root configurations is the best invention in the module ecosystem, and for three different reasons:
# modules/network/examples/complete/main.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
local = { source = "hashicorp/local", version = "~> 2.5" }
random = { source = "hashicorp/random", version = "~> 3.6" }
}
}
provider "local" {}
# The example is a ROOT module: here there is a provider and here it is applied.
module "network" {
source = "../../" # goes up two levels to modules/network/
base_name = "complete-example"
cidr = "10.90.0.0/16"
zones = ["eu-west-1a", "eu-west-1b", "eu-west-1c"]
create_nat = true
tags = {
Project = "example"
Environment = "test"
ManagedBy = "terraform"
}
}
output "network" {
value = module.network.network
}$ cd modules/network/examples/complete
$ terraform init
$ terraform apply -auto-approve
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.
Outputs:
network = {
"cidr" = "10.90.0.0/16"
"private_subnets" = {
"eu-west-1a" = "..."
"eu-west-1b" = "..."
"eu-west-1c" = "..."
}
"vpc_id" = "..."
"vpc_name" = "complete-example-vpc"
}
$ terraform destroy -auto-approveWhy they are worth maintaining:
- They are documentation that cannot lie. An example in the README can go stale without anybody noticing; an example in
examples/that runs in CI fails the day the interface changes. - They are the module's test bench. Developing a module without a root from which to apply it is extremely awkward. With
examples/completeyou have anapply/destroycycle that takes seconds. - They are the basis for automated tests. Both
terraform testand Terratest build on runnable examples. You will see this in detail in Testing Terraform Code.
The usual convention: at least examples/minimal/ (only the mandatory variables, to check that the defaults suffice) and examples/complete/ (every option switched on, to check that nothing breaks in combination). And a warning about source: examples use a relative path (../../) so as to test the local code, but the README must show the real, versioned source a consumer will use. Confusing the two means the README example does not work outside the repository.
- Guided exercise: extracting the network from the monolith with
moved
movedThe moment of truth arrives. You have EcoMarket's monolith applied, with its state populated, and you are going to pull the network out into modules/network without destroying anything.
Step 1: photograph the current state
Before touching anything, take the photo. This step is not optional: it is what will let you compare afterwards.
$ cd infra/app
$ terraform state list > /tmp/state-before.txt
$ cat /tmp/state-before.txt
local_file.db
local_file.images_bucket
local_file.load_balancer
local_file.network
local_file.service["api"]
local_file.service["batch"]
local_file.service["web"]
local_file.subnet["eu-west-1a"]
local_file.subnet["eu-west-1b"]
random_password.db
random_pet.suffix
tls_private_key.web
tls_self_signed_cert.webAnd a clean plan, to confirm you are starting from zero:
If this plan is not at zero, stop. Refactoring on top of a configuration with pending changes mixes two things in the same plan and stops you knowing whether the 0 to destroy you are after is real.
Step 2: create the module and delete the resources from the root
Create modules/network/ with the files from sections 2 to 11, and remove the local_file.network and local_file.subnet resources from infra/app/main.tf, replacing them with the call:
# infra/app/main.tf
module "network" {
source = "../../modules/network"
base_name = local.prefix
cidr = local.current.cidr
zones = var.zones
create_nat = local.current.create_nat
tags = local.common_tags
}Step 3: the plan without moved (so you see it with your own eyes)
Terraform will perform the following actions:
# local_file.network will be destroyed
# (because local_file.network is not in configuration)
- resource "local_file" "network" { ... }
# local_file.subnet["eu-west-1a"] will be destroyed
# (because local_file.subnet is not in configuration)
# local_file.subnet["eu-west-1b"] will be destroyed
# module.network.local_file.vpc will be created
+ resource "local_file" "vpc" { ... }
# module.network.local_file.subnet["eu-west-1a"] will be created
# module.network.local_file.subnet["eu-west-1b"] will be created
# module.network.local_file.base_security_group will be created
Plan: 4 to add, 0 to change, 3 to destroy.3 to destroy for a refactor that changes nothing real. With local_file it is harmless; with the production VPC it would be a total service outage.
Step 4: add the moved blocks
# infra/app/moved.tf
# Refactor 2026-09: extraction of the network layer into modules/network.
# Delete once dev, staging and prod have applied (see CHANGELOG).
moved {
from = local_file.network
to = module.network.local_file.vpc
}
moved {
from = local_file.subnet["eu-west-1a"]
to = module.network.local_file.subnet["eu-west-1a"]
}
moved {
from = local_file.subnet["eu-west-1b"]
to = module.network.local_file.subnet["eu-west-1b"]
}Notice that the first block changes two things at once: the module (local_file.network → module.network....) and the resource name (network → vpc). A single moved block covers both changes, because what it declares is the correspondence between two complete addresses, no matter how many pieces differ.
Step 5: the plan with moved
Terraform will perform the following actions:
# local_file.network has moved to module.network.local_file.vpc
resource "local_file" "vpc" {
id = "b6f0a1..."
# (5 unchanged attributes hidden)
}
# local_file.subnet["eu-west-1a"] has moved to module.network.local_file.subnet["eu-west-1a"]
# local_file.subnet["eu-west-1b"] has moved to module.network.local_file.subnet["eu-west-1b"]
# module.network.local_file.base_security_group will be created
+ resource "local_file" "base_security_group" { ... }
Plan: 1 to add, 0 to change, 0 to destroy.0 to destroy. The 1 to add is legitimate and you need to be able to explain it in the PR: the base security group is a new resource that the module contributes and that the monolith did not have. It is not a replacement in disguise; it is added functionality.
If you want a completely pure refactor — 0 to add, 0 to change, 0 to destroy — split the extraction into two PRs: first the literal move without adding anything, then the improvement. That separation is one of the best habits you can pick up: one PR that refactors and another that changes behaviour, never the two mixed, because in a mixed plan nobody can tell the move from the change.
Step 6: apply and verify
$ terraform apply
local_file.network has moved to module.network.local_file.vpc
...
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
$ terraform state list > /tmp/state-after.txt
$ diff /tmp/state-before.txt /tmp/state-after.txt
4d3
< local_file.network
8,9d6
< local_file.subnet["eu-west-1a"]
< local_file.subnet["eu-west-1b"]
9a7,10
> module.network.local_file.base_security_group
> module.network.local_file.subnet["eu-west-1a"]
> module.network.local_file.subnet["eu-west-1b"]
> module.network.local_file.vpcThe diff shows exactly what you expected: three resources that changed address and one new one. No identifier lost.
# The definitive proof: the ids are the same as before.
$ terraform state show module.network.local_file.vpc | grep '^\s*id'
id = "b6f0a1..." # the same one as before the refactorStep 7: repeat in all three environments and clean up
$ terraform init -reconfigure -backend-config=../../backends/staging.hcl && terraform apply
$ terraform init -reconfigure -backend-config=../../backends/prod.hcl && terraform applyOnly after all three environments have applied can the moved blocks be deleted. And since each environment's state is independent, deleting them too early means the environment that did not apply will destroy its network on the next apply. If in doubt, leave them: a moved whose from no longer exists is silently ignored and costs nothing.
Common Mistakes and Tips
-
Putting a
providerblock inside the module. The module becomes legacy and losescount,for_eachanddepends_on; on top of that, destroying it gets complicated. The module declaresrequired_providersand, if it needs several instances,configuration_aliases; configuring is the root's job. -
Using
path.rootto read the module's files. It works while the module is local and fails the day it is consumed from Git. Always read frompath.module; write, if anything, topath.root. -
Passing
var.environmentinto the module and branching inside. Acount = var.environment == "prod" ? 1 : 0inside a module ties it to your organisation, stops it being tested in isolation and forces you to touch it every time a new environment appears. The parent translates environment into parameters; the module only sees parameters. -
Pinning provider versions too narrowly in the module (
version = "5.31.0"). If another module in the same configuration asks for a different one,initfails with no possible solution. In modules, broad minimums (>= 5.0); the exact pin is set by the root in its lock file. -
Forgetting
sensitive = truewhen republishing a sensitive output. Terraform blocks it withOutput refers to sensitive values; the fix is to mark it, not to wrap it innonsensitive(). And remember thatsensitivedoes not encrypt state. -
Putting a sensitive value inside a composite object. It taints the whole object and you end up unable to see perfectly public data such as
vpc_idin theplan. Sensitive outputs, always separate. -
Tip: write
examples/complete/at the same time as the module, not afterwards. It gives you a runnable root for theapply/destroycycle while you develop and it forces you to use your own interface, which is the best way to notice that it is awkward. -
Tip:
terraform consoleworks in an isolated module directory if its variables havedefaultvalues or you pass them with-var. It is the quickest way to debug alocal.subnetswithout applying anything. -
Tip: in a refactor, separate the move PR from the improvement PR. A plan with
0 to add, 0 to change, 0 to destroyis approved in thirty seconds; a mixed plan forces the reviewer to tell by eye what is a move and what is a change, and that is exactly where replacements slip through.
Exercises
Exercise 1: designing the data module's interface
Following the allocation from 04-01, the data module will contain random_password.db, the simulated PostgreSQL instance and the images bucket.
- Write the ideal call to the module, before implementing it, with at most seven inputs.
- Classify these eight aspects into the three boxes (exposed / exposed with a
default/ fixed inside): engine version, instance class, backup retention days, encryption at rest, multi-AZ, port, bucket versioning, bucket name. - Write the complete
variables.tf, withtype,description,nullableand at least threevalidationblocks with useful messages. - Write the
outputs.tf, deciding explicitly what is not published and why.
Exercise 2: paths and templates
- Create in
modules/network/templates/asummary.txt.tftpltemplate that produces a human-readable summary of the network: VPC name, CIDR, number of subnets and one line per zone with its computed CIDR. - Add to the module a
local_file.summaryresource that uses it and writes the result into the consumer's output directory. - Run the
examples/completeexample and check the generated file. - Deliberately swap
path.moduleforpath.rootwhen reading the template, run it and note down the exact error. Explain in two lines why this bug is not caught if the module is local and the template is also copied in the root.
Exercise 3: guided extraction of the data module with moved
Repeat the exercise from section 14 with the data layer:
- Photograph the state (
terraform state list) and confirm the plan is at zero. - Create
modules/data/with the interface from exercise 1 and move therandom_password.db,local_file.dbandlocal_file.images_bucketresources. - Plan without
movedblocks and note the number of destructions. Pay particular attention torandom_password.db: what would happen in real life if it were recreated? - Add the necessary
movedblocks and verify0 to destroy. - The
datamodule needs the random suffix, which lives in the root. How do you pass it in? Why do you not move it inside the module? - Apply and prove with
terraform state showthat the generated password is the same as before the refactor.
Solutions
Solution 1
Point 1 — ideal call:
module "data" {
source = "./modules/data"
base_name = local.prefix
suffix = random_pet.suffix.id
subnets = module.network.private_subnets
size = local.current.db_size # "small" | "medium" | "large"
high_availability = local.current.multi_az
retention_days = local.current.retention_days
tags = local.common_tags
}The interesting design decision is size rather than instance_class: it exposes intent, not implementation. The module internally translates "medium" into the concrete class, and the day the instance family changes, consumers never notice. It is the exact opposite of the provider-mirror antipattern.
Point 2 — the three boxes:
| Aspect | Box | Reason |
|---|---|---|
| Engine version | Exposed with a default |
It changes over time, but there must be a recommended one. default = "16.3" |
| Instance class | Fixed inside (derived from size) |
It is implementation; what gets exposed is the intent |
| Retention days | Exposed with a default |
It legitimately differs between dev (7) and prod (30) |
| Encryption at rest | Fixed inside | Security policy: always on, with no option to switch it off |
| Multi-AZ | Exposed with default = false |
A real cost difference between environments |
| Port | Fixed inside (5432) | Changing it adds no security and breaks every client |
| Bucket versioning | Fixed inside | Policy: it protects against accidental deletions |
| Bucket name | Fixed inside (derived) | It is computed as <base_name>-images-<suffix>; exposing it would allow inconsistent names |
Point 3 — variables.tf:
# modules/data/variables.tf
variable "base_name" {
description = "Prefix used to name the data resources."
type = string
nullable = false
}
variable "suffix" {
description = "Random suffix guaranteeing unique bucket names. Generated by the root module."
type = string
nullable = false
validation {
condition = can(regex("^[a-z0-9-]{3,20}$", var.suffix))
error_message = "suffix must be lower-case letters, digits or hyphens (3-20 characters)."
}
}
variable "subnets" {
description = "Map from zone to private subnet identifier in which to place the database."
type = map(string)
nullable = false
validation {
condition = length(var.subnets) >= 2
error_message = "PostgreSQL needs at least 2 subnets in different zones. Received: ${length(var.subnets)}."
}
}
variable "size" {
description = "Logical sizing of the database: small, medium or large."
type = string
default = "small"
validation {
condition = contains(["small", "medium", "large"], var.size)
error_message = "size must be 'small', 'medium' or 'large'. Received: '${var.size}'."
}
}
variable "engine_version" {
description = "Major.minor version of PostgreSQL."
type = string
default = "16.3"
validation {
condition = can(regex("^1[4-9]\\.[0-9]+$", var.engine_version))
error_message = "Only PostgreSQL 14 or above is supported. Received: '${var.engine_version}'."
}
}
variable "high_availability" {
description = "Deployment across several zones. It doubles the cost; recommended in production only."
type = bool
default = false
}
variable "retention_days" {
description = "Retention in days of the automated backups."
type = number
default = 7
validation {
condition = var.retention_days >= 1 && var.retention_days <= 35
error_message = "retention_days must be between 1 and 35. Received: ${var.retention_days}."
}
}
variable "tags" {
description = "Tags applied to every resource in the module."
type = map(string)
default = {}
nullable = false
}The translation from size to implementation lives in a local:
# modules/data/locals.tf
locals {
classes = {
small = { class = "db.t3.micro", storage = 20 }
medium = { class = "db.t3.small", storage = 100 }
large = { class = "db.r6g.large", storage = 500 }
}
sizing = local.classes[var.size]
}Point 4 — outputs.tf:
output "endpoint" {
description = "Host and port of the database, in host:port form."
value = "${local.db_name}.internal.ecomarket.example.com:5432"
}
output "db_name" {
description = "Logical name of the instance."
value = local.db_name
}
output "bucket_id" {
description = "Identifier of the images bucket."
value = local_file.images_bucket.id
}
output "bucket_name" {
description = "Full bucket name, with the suffix already applied."
value = local.bucket_name
}What is not published, and why:
| Not published | Reason |
|---|---|
random_password.db.result |
It would be a secret crossing layers and it would be marked sensitive, tainting any object that included it. The application should read it from a secrets manager, not from a Terraform output |
| The full connection string | Same reason: it contains the password |
local.sizing |
It is internal implementation; publishing it would turn the translation table into a contract and you could no longer change it |
Solution 2
Point 1 — template:
# modules/network/templates/summary.txt.tftpl
Network: ${name}
CIDR: ${cidr}
Subnets: ${length(zones)}
%{ for i, z in zones ~}
- ${z}: ${cidrsubnet(cidr, bits, i)}
%{ endfor ~}
Contact: [email protected]Point 2 — resource:
resource "local_file" "summary" {
filename = "${path.root}/output/${var.base_name}-summary.txt"
content = templatefile("${path.module}/templates/summary.txt.tftpl", {
name = local.vpc_name
cidr = var.cidr
zones = var.zones
bits = var.subnet_bits
})
}Both paths play their part: path.module to read what travels with the module, path.root to write into the consumer's project.
Point 3 — result:
$ cat output/complete-example-summary.txt Network: complete-example-vpc CIDR: 10.90.0.0/16 Subnets: 3 - eu-west-1a: 10.90.0.0/24 - eu-west-1b: 10.90.1.0/24 - eu-west-1c: 10.90.2.0/24 Contact: [email protected]
Point 4 — the error:
╷
│ Error: Invalid function argument
│
│ on ../../main.tf line 5, in resource "local_file" "summary":
│ 5: content = templatefile("${path.root}/templates/summary.txt.tftpl", {
│
│ Invalid value for "path" parameter: no file exists at
│ "./templates/summary.txt.tftpl".
╵Why it is not caught with local modules: if the module is in ./modules/network and by chance ./templates/summary.txt.tftpl also exists in the root — which is very likely during the extraction from the monolith, when the template used to live there — path.root resolves to a file that does exist and the code works. The failure appears the day another repository consumes the module from Git and does not have that directory. It is a latent bug that only shows up on publication, which is the worst possible moment. The defence is to run the module from examples/, which already has a path.root different from your project's.
Solution 3
Point 3 — plan without moved:
The serious one is random_password.db. With the random provider, a resource that is destroyed and recreated generates a new password: the value is not deterministic and there is no way to recover the previous one. In a real deployment that means the database keeps the old password while Terraform and the application move to the new one, and the application stops connecting until somebody syncs them by hand. It is exactly the kind of silent breakage that makes refactors frightening, and the reason why random_* resources are among those that benefit most from moved.
Point 4 — moved blocks:
moved {
from = random_password.db
to = module.data.random_password.db
}
moved {
from = local_file.db
to = module.data.local_file.instance
}
moved {
from = local_file.images_bucket
to = module.data.local_file.images_bucket
}Point 5 — the suffix:
It is passed in as a variable from the root:
It is not moved inside the module for two reasons. The first, already seen in 04-01: data and app share it, and if it lived in data, app would depend on data for a reason unrelated to data. The second is about module design and is more general: a module that generates on its own the values that identify it is harder to test and to compose. If the suffix comes in as a variable, you can pin it in a test and get deterministic names; if it is generated inside, every apply produces different names and there is no way to write an assertion about them. That idea — passing dependencies in rather than discovering them — is the dependency injection of 04-05.
Point 6 — verification:
$ terraform state show module.data.random_password.db | grep -E '^\s*(id|result)'
id = "none"
result = (sensitive value)
# To compare the real value without printing it on screen, compare its hash
# before and after the refactor:
$ terraform output -raw db_password_hash
a3f5c9e1... # identical to the one from before the refactorThe value being sensitive does not stop you verifying it: it is enough to publish an output temporarily with sha256() of the secret and compare the fingerprints before and after. It is a useful technique whenever you need to check that a secret has not changed without ever printing it into any log.
Conclusion
You have written a whole module and, more importantly, you have written one that somebody else can use without asking you anything:
- Interface first, implementation second. Write the ideal call before the
main.tfand classify every aspect into exposed / exposed with adefault/ fixed inside. The third box is what gives the module its value: a good module has opinions. And remember the asymmetry: widening the interface is cheap, narrowing it is a major version. - The
variables.tfis a contract:typealways,descriptionalways — because it is whatterraform-docspublishes —,nullable = falseon everything mandatory and severalvalidationblocks with messages that say what value arrived and what was expected. - The
outputs.tfpublishes identifiers, derived values and a composite object that lets you add fields without breaking anybody. Sensitivity propagates: republishing a sensitive output requiressensitive = true, and a secret inside a composite object taints the whole object. - The
versions.tfdeclaresrequired_versionandrequired_providerswith noproviderblock at all: adding one would turn the module into a legacy one, withoutcount,for_eachordepends_on, and would complicate its destruction. Broad constraints in the module, exact ones in the root. When two instances are needed,configuration_aliasesandproviders = {}in the parent. path.moduleto read,path.rootto write. It is the bug that works locally and fails on publication.- Internal
localsare private and serve to compute first and create afterwards: a well-builtlocal.subnetsmap leaves the resource trivial, with stable keys and everything inspectable fromterraform console. - Tagging is solved by accepting
var.tagsand merging it withmerge(), where the right-hand side wins; and the principal resource is calledthisormain, a name that is not changed lightly because it is a state address. README.mdwithterraform-docsmarkers, and runnableexamples/minimalandexamples/complete: documentation that cannot lie, a test bench and the basis for the automated tests of 07-03.- And the central exercise: EcoMarket's network came out of the monolith into
modules/networkwith threemovedblocks, going from3 to destroyto0 to destroy, with identifiers intact and thestate listdiffas proof. One PR to move, another to improve.
The network module exists and works, but you have only called it in the simplest way possible: source = "../../modules/network" and four variables. In the next lesson, Using Modules, you turn the problem around and look at the module block from the outside: every form of source and what each one implies for reproducibility, version versus ref=, the count, for_each, depends_on and providers meta-arguments — with EcoMarket's replica in another region —, what terraform init does exactly when it downloads modules into .terraform/modules/, how to debug somebody else's module with terraform console, and how deep it is worth nesting before falling into infinite passthrough.
