terraform-aws-ecomarket-network is published and it has consumers: ecomarket-infra and ecomarket-wholesale. From here on, every change you make to that module can break another team's infrastructure, and that changes the way you work completely. This lesson closes module 4 with the two disciplines that turn a pile of modules into a platform: composing them — how they stack, how dependencies are passed, when it is better to split into separate configurations — and versioning them — what MAJOR means when what changes is not a function but a database, and how to evolve without leaving anybody stranded.
- Composition versus inheritance
In object-oriented programming there is a classic piece of advice: prefer composition over inheritance. In Terraform the discussion does not even exist, because inheritance is not available: there is no way for one module to "extend" another, override part of its behaviour or redefine one of its resources. The only way to build on another module is to call it.
That, which looks like a limitation, is one of the language's best design decisions. And it is worth understanding why, because it explains a lot of frustration for people coming from other languages:
| What you would like to do (inheritance) | What Terraform forces you to do (composition) |
|---|---|
"I want the network module but with the CIDR computed differently" |
Expose the computation as a variable, or compute it outside and pass it in |
"I want the data module without the bucket" |
Give the module a create_bucket variable, or split it into two modules |
| "I want to add a tag to one particular resource in the module" | Have the module accept per-resource tags, or tag everything the same |
| "I want to change a rule in the security group the module creates" | Have the module expose the rules, or create a separate group |
The pattern repeats: what is not in the interface cannot be changed from outside. There is no back door, no monkey patching, no way of reaching an internal resource. It is inconvenient when you need something the module did not anticipate, and it is what makes a module reasonable to maintain: its author knows exactly which contracts it has.
There are two partial escape hatches, and it is worth knowing their limits:
# 1. Adding resources OUTSIDE the module that build on its outputs.
module "network" {
source = "./modules/network"
# ...
}
resource "local_file" "extra_rule" {
filename = "output/extra-rule.json"
content = jsonencode({
vpc = module.network.vpc_id # builds on the output
port = 9090
})
}This always works and it is the right answer to 80% of "I need something extra". The extra resource is yours, you manage it, and the module never knows.
Terraform accepts *_override.tf files that override blocks from other files in the same module. It cannot be used to modify child modules and its use is explicitly discouraged by HashiCorp: it makes the code impossible to read, because a resource can be defined in one place and modified in another with no reference between the two. It is mentioned here so you recognise it if you see it in an old repository, not so that you use it.
- Leaf modules and composition modules
With composition as the only tool, modules fall into two families, and telling them apart is what avoids the monolith-module antipattern:
| Leaf module (or resource module) | Composition module (or platform module) | |
|---|---|---|
| What it contains | resource and data blocks |
module blocks, almost no resource |
| Example | network, data, app |
ecomarket-platform |
| Size of the interface | Medium: technical parameters | Small: business parameters |
| Reuse | High, in many contexts | Low: it is specific to the organisation |
| Versioning | Strict, many consumers | More relaxed, few consumers |
| Tests | Unit: deploy and verify | Integration: deploy everything |
| Who maintains it | The platform team | The platform or product team |
The golden rule: a composition module does not create resources, it orchestrates modules. The moment you start mixing twenty resource blocks with five module blocks in the same directory, you are back to the monolith with extra steps.
EcoMarket's layers end up like this:
flowchart TB
subgraph L3["Root configurations — one per environment and component"]
C1["infra/app (dev)"]
C2["infra/app (staging)"]
C3["infra/app (prod)"]
C4["ecomarket-wholesale/infra"]
end
subgraph L2["Composition module"]
P["ecomarket-platform v1.4.0<br/><i>2 variables: base_name, profile</i>"]
end
subgraph L1["Leaf modules — published and versioned"]
N["ecomarket-network<br/>v2.1.0"]
D["ecomarket-data<br/>v1.3.2"]
A["ecomarket-app<br/>v3.0.1"]
end
subgraph L0["Provider resources"]
X["aws_vpc · aws_subnet · aws_db_instance<br/>aws_s3_bucket · aws_lb · aws_autoscaling_group"]
end
C1 --> P
C2 --> P
C3 --> P
C4 --> N
P --> N
P --> D
P --> A
N --> X
D --> X
A --> X
style P fill:#fff6e5,stroke:#b7791f
style N fill:#e9f7ef,stroke:#2f855a
style D fill:#e8f0fe,stroke:#1a73e8
style A fill:#f3e8fd,stroke:#7c3aed
Notice ecomarket-wholesale: it consumes only the network module, without going through the platform. That is the proof that the layers are well placed — leaf modules are useful on their own — and it is exactly what a monolith module would prevent.
- The
ecomarket-platform module
ecomarket-platform module# terraform-aws-ecomarket-platform/variables.tf
variable "base_name" {
description = "Naming prefix: '<project>-<environment>'."
type = string
nullable = false
}
variable "profile" {
description = <<-EOT
The platform's sizing profile. It translates a business intention
into concrete technical decisions:
- minimal : development environments. No NAT, no HA, 1 web.
- standard : pre-production. NAT, medium DB, 2 webs.
- high : production. NAT, large DB, multi-AZ, 4 webs, read replica.
EOT
type = string
validation {
condition = contains(["minimal", "standard", "high"], var.profile)
error_message = "profile must be 'minimal', 'standard' or 'high'. Received: '${var.profile}'."
}
}
variable "cidr" {
description = "CIDR block of this platform instance's network."
type = string
}
variable "zones" {
description = "Availability zones to use."
type = list(string)
}
variable "db_password" {
description = "PostgreSQL password. Injected from TF_VAR_db_password."
type = string
sensitive = true
}
variable "tags" {
description = "Common tags."
type = map(string)
default = {}
}# terraform-aws-ecomarket-platform/main.tf
locals {
# HERE is the composition module's value: translating intent into technique.
profiles = {
minimal = {
nat = false
db_size = "small"
db_multi_az = false
db_retention = 7
web_instances = 1
read_replica = false
}
standard = {
nat = true
db_size = "medium"
db_multi_az = false
db_retention = 14
web_instances = 2
read_replica = false
}
high = {
nat = true
db_size = "large"
db_multi_az = true
db_retention = 30
web_instances = 4
read_replica = true
}
}
p = local.profiles[var.profile]
tags = merge(var.tags, {
Platform = "ecomarket"
PlatformProfile = var.profile
PlatformVersion = "1.4.0"
})
}
# Shared resource: it lives here because two child modules use it.
resource "random_pet" "suffix" {
length = 2
}
module "network" {
source = "ecomarket/ecomarket-network/aws"
version = "~> 2.1.0"
base_name = var.base_name
cidr = var.cidr
zones = var.zones
create_nat = local.p.nat
tags = local.tags
}
module "data" {
source = "ecomarket/ecomarket-data/aws"
version = "~> 1.3.0"
base_name = var.base_name
suffix = random_pet.suffix.id
subnets = module.network.private_subnets # explicit injection
size = local.p.db_size
high_availability = local.p.db_multi_az
retention_days = local.p.db_retention
tags = local.tags
}
module "app" {
source = "ecomarket/ecomarket-app/aws"
version = "~> 3.0.0"
base_name = var.base_name
suffix = random_pet.suffix.id
network = module.network.network # composite object
db_endpoint = module.data.endpoint
bucket_id = module.data.bucket_id
db_password = var.db_password # the secret by the short route
instances = local.p.web_instances
tags = local.tags
}
module "read_replica" {
count = local.p.read_replica ? 1 : 0
source = "ecomarket/ecomarket-data/aws"
version = "~> 1.3.0"
base_name = "${var.base_name}-ro"
suffix = random_pet.suffix.id
subnets = module.network.private_subnets
size = local.p.db_size
tags = merge(local.tags, { Role = "read-replica" })
}And an environment's root configuration is reduced to this:
# ecomarket-infra/infra/app/main.tf
module "platform" {
source = "ecomarket/ecomarket-platform/aws"
version = "~> 1.4.0"
base_name = "${var.project}-${var.environment}"
profile = local.current.profile # "minimal" | "standard" | "high"
cidr = local.current.cidr
zones = var.zones
db_password = var.db_password
tags = local.common_tags
}
output "endpoints" {
value = module.platform.endpoints
}Compare this with the 340-line main.tf we started from in 04-01. The whole journey of module 4 fits into that comparison: from a file that did too much to six arguments and one output, with every technical decision encapsulated in the layer it belongs to and versioned separately.
- Dependency injection between modules
There are two ways for data to know which subnets to deploy into. And the choice between them determines whether your modules are reusable or not.
Option A — discovery (the module looks for what it needs):
# INSIDE modules/data/main.tf — discovery
data "aws_vpc" "main" {
filter {
name = "tag:Name"
values = ["${var.base_name}-vpc"]
}
}
data "aws_subnets" "private" {
filter {
name = "vpc-id"
values = [data.aws_vpc.main.id]
}
filter {
name = "tag:Tier"
values = ["private"]
}
}
resource "aws_db_subnet_group" "db" {
subnet_ids = data.aws_subnets.private.ids
}Option B — injection (the parent passes in what it needs):
# INSIDE modules/data/variables.tf — injection
variable "subnets" {
description = "Map from zone to private subnet identifier."
type = map(string)
nullable = false
}
resource "aws_db_subnet_group" "db" {
subnet_ids = values(var.subnets)
}On the face of it A is more convenient: the consumer writes less. In practice it is worse at almost everything:
| Criterion | Discovery (A) | Injection (B) |
|---|---|---|
| Lines in the call | Fewer | One more |
| Implicit dependency | Yes: nothing in the graph says the network must exist first | No: the reference creates the edge |
| Guaranteed ordering | No: it can fail on a race condition during the first apply |
Yes |
| Coupling | To your organisation's tagging scheme | Only to a data type |
| Reusable in another organisation | No: the tags would be different | Yes |
| Testable in isolation | No: you need a real VPC with those tags | Yes: you pass fake identifiers |
| Permissions required | Read on DescribeVpcs, DescribeSubnets |
None extra |
Visible in the plan |
The data block resolves and can change without warning |
The value comes from a known output |
| Errors | no matching VPC found, without saying what it was looking for |
A type error, clear and early |
The implicit-dependency row is the one that causes real incidents. With discovery, Terraform does not know that data depends on network: the data block is evaluated when its turn comes and, on an apply from scratch, it can run before the VPC exists. The result is an intermittent failure that only shows up on new deployments and never on incremental ones, which is the worst kind of bug.
Rule: inject whenever the value is produced by another part of your own configuration. Discovery with data is justified only when the resource is genuinely external:
# Legitimate: the VPC is managed by another team, in another state, outside your control.
data "aws_vpc" "corporate" {
tags = { Name = "shared-corporate-vpc" }
}
# Legitimate: data from the provider itself, not from your infrastructure.
data "aws_availability_zones" "available" {
state = "available"
}
data "aws_caller_identity" "current" {}And an in-between variant that appears in large organisations: the module accepts injection and supports discovery as a fallback.
variable "vpc_id" {
description = "VPC identifier. If null, it is discovered by tag."
type = string
default = null
}
data "aws_vpc" "discovered" {
count = var.vpc_id == null ? 1 : 0
tags = { Name = "${var.base_name}-vpc" }
}
locals {
vpc_id = coalesce(var.vpc_id, try(data.aws_vpc.discovered[0].id, null))
}It is flexible and it has a cost worth acknowledging: it doubles the execution paths and therefore what has to be tested. Use it only if there is a real need, not just in case.
- Module or separate configuration?
This is the most important structural decision in the whole architecture, and it closes the thread you left open in 04-01: a module organises code; only a separate configuration organises state.
| Module | Separate configuration | |
|---|---|---|
| State | Shared with the parent | Its own |
| Locking | Shared | Its own: two teams apply at the same time |
plan duration |
The sum of everything | Only its own part |
| Blast radius of a bug | The whole configuration | Only that component |
| Permissions | Those of whoever runs everything | Can be restricted per component |
| Passing data | Direct: module.network.vpc_id |
terraform_remote_state or data sources |
| Deployment order | Automatic (the graph) | Manual or driven by the pipeline |
| Refactoring between the two | moved |
state mv between states, or import |
The five criteria that decide, in order of weight:
| Criterion | Question | Separate if… |
|---|---|---|
| Rate of change | How often does each part change? | One changes daily and the other twice a year |
| Blast radius | What happens if an apply goes wrong? |
A bug in the app must not be able to touch the database |
| Permissions | Who should be able to apply each part? | The product team deploys the app but not the network |
apply duration |
How long does it take? | The full plan goes past 3–5 minutes |
| Organisational boundary | Is it maintained by the same team? | They are different teams with different cycles |
Applied to EcoMarket, the decision was already made back in module 3 and now it makes full sense:
ecomarket/<environment>/network/terraform.tfstate ← infra/network : changes quarterly ecomarket/<environment>/app/terraform.tfstate ← infra/app : changes weekly
networkseparated: it changes rarely, a mistake there affects everything, and only the platform team should be able to touch it.dataandapptogether ininfra/app: they change at the same rate, they are deployed together and the same team maintains them. They are modules, not configurations.
And the bridge between the two is the terraform_remote_state from Remote State:
# infra/app/main.tf
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "ecomarket-tfstate"
key = "ecomarket/${var.environment}/network/terraform.tfstate"
region = "eu-west-1"
}
}
module "data" {
source = "ecomarket/ecomarket-data/aws"
version = "~> 1.3.0"
subnets = data.terraform_remote_state.network.outputs.private_subnets
# ...
}Notice that the data module does not change at all. It does not care whether the value comes from module.network.private_subnets or from a remote state: it receives a map(string). That indifference is precisely the reward for having chosen injection rather than discovery: the same piece works in both architectures, and you can move the boundary between module and configuration without rewriting anything.
The warning from 03-03 still stands: terraform_remote_state requires read permission on the other component's entire state, secrets included. Between different teams, use provider data sources or a parameter store.
- Semantic versioning applied to infrastructure
SemVer is MAJOR.MINOR.PATCH and everybody thinks they know it. Applied to infrastructure there is a twist that changes everything:
In software, a breaking change means the consumer's code does not compile. In infrastructure, a breaking change means the consumer's infrastructure is destroyed.
That forces you to widen the definition of MAJOR. A Terraform module has two contracts, not one:
| Contract | What it is | How it breaks |
|---|---|---|
| Interface contract | The variable and output blocks |
Renaming, removing or making a variable required; renaming or removing an output |
| State contract | The addresses of the resources it creates | Renaming a resource, moving it into a submodule, going from count to for_each |
The second one is invisible in the consumer's code and it is the one that destroys databases. A module that renames aws_vpc.main to aws_vpc.this does not change a single line of the interface, and it is still a MAJOR change.
There is also a third kind of change that does not fit any software scheme:
| Contract | What it is | How it breaks |
|---|---|---|
| Behaviour contract | What the resulting infrastructure does | A default value that causes a resource replacement, or that changes cost or security significantly |
Changing the default value of storage_type from gp2 to gp3 touches neither the interface nor the addresses, but on the real provider it triggers an in-place modification that can take hours and degrade performance. If the attribute were one of those that force replacement, it would destroy the volume. A default-value change that produces must be replaced is MAJOR, however minor an adjustment it looks.
- Classifying a change: the decision table
| Change | Level | Why |
|---|---|---|
Adding a variable with a default |
MINOR | Nobody breaks; whoever does not use it carries on the same |
Adding a variable without a default |
MAJOR | Every consumer fails with No value for required variable |
| Renaming a variable | MAJOR | Unsupported argument in every consumer |
Making a variable optional (adding a default) |
MINOR | It widens what is accepted; nobody breaks |
| Making an optional variable required | MAJOR | It breaks whoever was not passing it |
Widening the type (string → any, adding optional()) |
MINOR | It accepts more than it used to |
Narrowing the type (any → string) |
MAJOR | It rejects values it used to accept |
Adding a stricter validation |
MAJOR | Valid configurations stop being valid |
| Adding an output | MINOR | Nobody was using it yet |
| Renaming or removing an output | MAJOR | This object does not have an attribute named… |
| Adding a field to a composite output object | MINOR | Whoever reads other fields carries on the same |
| Adding a new resource to the module | MINOR | It shows up as to add, it destroys nothing |
| Removing a resource from the module | MAJOR | It destroys existing infrastructure |
Renaming an internal resource without moved |
MAJOR | Destroy + create in every consumer |
Renaming an internal resource with moved |
MINOR | The consumer sees has moved to, 0 to destroy |
Going from count to for_each without moved |
MAJOR | Mass reindexing |
Changing a default with no effect on the plan |
PATCH | Nobody notices |
Changing a default that causes a modification |
MINOR | It changes behaviour; it has to be documented |
Changing a default that causes a replacement |
MAJOR | It destroys and recreates the resource |
Raising the required_version minimum |
MAJOR | Whoever is on an earlier version cannot use it |
Raising the required_providers minimum |
MINOR or MAJOR | MINOR if broad; MAJOR if it excludes versions in use |
Fixing a bug without changing the plan |
PATCH | Invisible to the consumer |
Improving the README or the description fields |
PATCH | No functional effect |
Adding a moved to ease a migration |
PATCH | It only helps; it is idempotent |
Three concrete examples on ecomarket-network, to settle the criterion:
Case 1 — a safer default CIDR. The base security group allowed 0.0.0.0/0 on port 443 and it is changed to var.cidr. The interface does not change; neither do the addresses. But for a consumer who depended on that opening, traffic stops flowing: a production incident, even though the change is a security improvement. It is MAJOR, and the CHANGELOG announces it as such with instructions on what to check.
Case 2 — adding enable_flow_log. A new resource that did not exist before is added, controlled by a variable with default = true. It shows up as 1 to add in every consumer's plan. It destroys nothing, but it costs money. Technically it is MINOR; the healthy practice is to publish it as MINOR and highlight it in the CHANGELOG, because a bill that goes up without warning erodes trust in the module more than a bug does.
Case 3 — renaming local_file.vpc to local_file.main with moved included. With the moved block inside the module, the consumer sees has moved to and 0 to destroy. It is MINOR. Without the block, exactly the same change is MAJOR and destructive. The difference between MAJOR and MINOR is five lines of moved, and that is the central idea of section 9.
- Version constraints in consumers
version = "2.1.0" # exactly that one
version = "~> 2.1.0" # >= 2.1.0 and < 2.2.0 (PATCH only)
version = "~> 2.1" # >= 2.1.0 and < 3.0.0 (MINOR and PATCH)
version = ">= 2.1.0" # anything from that one on. Dangerous
version = ">= 2.1, < 3.0" # an explicit range, equivalent to ~> 2.1
version = "!= 2.3.0" # an exclusion, to skip a version with a bugThe ~> ("pessimistic") operator increments the last component you write, and that is the rule people forget:
| Constraint | Allows | Does not allow |
|---|---|---|
~> 2.1.0 |
2.1.1, 2.1.9 |
2.2.0, 3.0.0 |
~> 2.1 |
2.1.1, 2.5.0, 2.99.0 |
3.0.0 |
~> 2 |
2.5.0, 2.99.0 |
3.0.0 |
And the indispensable reminder from 04-03: there is no module lock file. With providers, .terraform.lock.hcl freezes the resolved version and the whole team uses the same one. With modules, every init -upgrade re-evaluates the range independently, so two environments on ~> 2.1 can be on 2.1.0 and 2.5.3 at the same time with nothing indicating it.
Hence EcoMarket's policy:
| Context | Constraint | Reason |
|---|---|---|
Own modules in prod |
~> 2.1.0 |
Patches only. MINORs come in when it is decided, not when somebody runs init -upgrade |
Own modules in dev/staging |
~> 2.1 |
Picks up MINORs early: dev is where problems should show up |
| Third-party modules in any environment | ~> 5.8.0 |
Maximum caution: the code is not ours |
| The composition module from the root | ~> 1.4.0 |
It is the contract with the environments |
| While developing a module | Local path ../../modules/x |
Immediate iteration without init |
| Never | >= x.y.z with no upper bound |
A MAJOR would come in unreviewed |
And a process rule that rounds it off: dev is always one or two versions ahead of prod. If a new version is going to cause problems, they should show up in dev a week before reaching production.
moved inside the module: the compatibility contract
moved inside the module: the compatibility contractThis is where the promise you made in 03-05 falls due: in a public module, keep the moved blocks until the next major version change, because they are part of its compatibility contract.
The key mechanism is that a moved block inside the module is applied in each consumer's state. The author writes the move once, and everybody who upgrades runs it automatically. Without that, every consumer would have to run terraform state mv by hand in every environment, and you already know how that ends: somebody does not do it and destroys something.
# terraform-aws-ecomarket-network/moved.tf — v2.2.0
# v2.2.0: the principal resource goes from "vpc" to "main" for consistency
# with the rest of EcoMarket's modules.
moved {
from = local_file.vpc
to = local_file.main
}
# v2.1.0: subnets went from count to for_each by zone.
# Kept until v3.0.0 (see CHANGELOG).
moved {
from = local_file.subnet[0]
to = local_file.subnet["eu-west-1a"]
}
moved {
from = local_file.subnet[1]
to = local_file.subnet["eu-west-1b"]
}What the consumer experiences:
$ # change version from "~> 2.1.0" to "~> 2.2.0"
$ terraform init -upgrade
$ terraform plan
# local_file.vpc has moved to local_file.main
Plan: 0 to add, 0 to change, 0 to destroy.Zero work on their part. Five rules to make this actually work:
- Addresses are relative to the module. Inside the module you write
local_file.vpc, notmodule.network.local_file.vpc. Terraform resolves the prefix in each consumer, whatever name they gave themoduleblock. - Keep the
movedblocks at least until the next MAJOR. A consumer can jump from2.0.0to2.9.0in one go and needs to walk the whole chain. - Document in a comment which version introduced each one. It is the only thing that lets you decide when they can be deleted.
- The clean-up goes in the MAJOR. Deleting the
movedblocks is a breaking change for anyone coming from far back, which is why its place is the major version, announced in theCHANGELOG: "v3.0.0: the 2.x seriesmovedblocks have been removed. Upgrade to 2.9.x first, apply, and then move to 3.0.0." - The
movedblocks accumulate, and that is fine. Amoved.tffile with fifteen blocks commented by version is not technical debt: it is the module's compatibility history.
The limits, worth knowing so you do not over-promise:
| Situation | Does moved solve it? |
Alternative |
|---|---|---|
| Renaming a resource | Yes | — |
| Moving into a submodule | Yes | — |
Going from count to for_each |
Yes, one block per instance | — |
Changing the resource type (aws_instance → aws_autoscaling_group) |
No | Document a manual migration with import/removed |
| Splitting one resource into two | No | moved for one, import or creation for the other |
| Merging two resources into one | No | removed with destroy = false + import |
| Changing an attribute that forces replacement | No: moved moves addresses, it does not prevent replacements |
Announce it as MAJOR and document it |
That last row is the most frequent confusion: moved does not protect against replacements, only against address changes. If the new version changes an attribute the provider marks as ForceNew, the resource will be destroyed and recreated however many moved blocks you add.
- Deprecated variables: warn before breaking
Terraform does not have a deprecated attribute on variable blocks. It has to be simulated, and there are three techniques with different degrees of harshness.
Technique 1 — document and keep both (the recommended one).
variable "create_nat" {
description = "DEPRECATED since v2.3.0: use 'nat' instead. It will be removed in v3.0.0."
type = bool
default = null # null = it was not used
}
variable "nat" {
description = "NAT gateway configuration."
type = object({
create = optional(bool, true)
per_zone = optional(bool, false)
})
default = {}
}
locals {
# The old variable wins if it was used, so as not to change the behaviour
# of anybody who has not migrated yet.
effective_nat = {
create = var.create_nat != null ? var.create_nat : var.nat.create
per_zone = var.nat.per_zone
}
}With this, v2.3.0 is still MINOR: whoever was using create_nat carries on working exactly the same, and whoever wants to can move to nat. Removing create_nat comes in v3.0.0.
Technique 2 — a visible warning via check (Terraform 1.5+).
check "deprecated_variable" {
assert {
condition = var.create_nat == null
error_message = "WARNING: the 'create_nat' variable has been deprecated since v2.3.0 and will be removed in v3.0.0. Replace it with 'nat = { create = ... }'. See the CHANGELOG."
}
}A failing check block produces a warning, not an error: the plan carries on and so does the apply. It is exactly what you want for a deprecation, and it is the closest thing to an @deprecated the language offers. check blocks are studied in depth in Preconditions, Postconditions and check.
Technique 3 — a failing validation (the harsh one).
variable "create_nat" {
type = bool
default = null
validation {
condition = var.create_nat == null
error_message = "The 'create_nat' variable was removed in v3.0.0. Use 'nat = { create = ... }'."
}
}This breaks the plan, so it is MAJOR by definition. Its value is not to warn but to give a comprehensible error instead of the generic Unsupported argument, which does not say what to use instead. It is a courtesy that costs four lines and is enormously appreciated.
The complete sequence of a well-executed deprecation:
| Version | What is done | What the consumer sees |
|---|---|---|
2.3.0 (MINOR) |
nat is added; create_nat still works; a check warns |
A warning in the plan. Everything works |
2.4.0 – 2.9.x |
Both coexist; the CHANGELOG repeats it in every version |
A warning in the plan |
3.0.0 (MAJOR) |
create_nat is removed; the explanatory validation remains |
A clear error with instructions |
3.1.0 |
The validation is removed too |
A generic Unsupported argument |
Practical rule: a deprecated variable lives for at least one full minor version before disappearing, and its disappearance is always MAJOR.
- The
CHANGELOG.md people actually read
CHANGELOG.md people actually readWithout a CHANGELOG, the only way to know what a version brings is to read the git log or the diff. With one, upgrading is an informed two-minute decision.
# Changelog
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
This module follows [Semantic Versioning](https://semver.org/) adapted to
infrastructure: a change is MAJOR if it can **destroy or replace** existing
resources, even when the interface does not change.
## [Unreleased]
## [3.0.0] - 2026-11-04
### ⚠️ Breaking changes
- **Removed the `create_nat` variable** (deprecated since 2.3.0).
Replace it with `nat = { create = true }`.
- **Removed the 2.x series `moved` blocks.**
If you are coming from a version earlier than 2.9.0, upgrade to `2.9.x`
first, run `apply`, and then jump to `3.0.0`.
- **The base security group no longer allows `0.0.0.0/0` on port 443**;
it is now restricted to `var.cidr`. If you relied on access from the
internet, add the rule explicitly outside the module.
### How to migrate
```bash
# 1. In dev, move up to 2.9.x and apply
terraform init -upgrade && terraform apply
# 2. Change the call
# - create_nat = true
# + nat = { create = true }
# 3. Move up to 3.0.0 and REVIEW THE PLAN before applying
terraform init -upgrade && terraform plan
```
Expected plan in an environment with no functional changes:
`0 to add, 1 to change, 0 to destroy` (the security group).
**If you see any `to destroy`, do not apply and open an issue.**
## [2.9.1] - 2026-10-12
### Fixed
- The subnet computation failed with `subnet_bits = 12` and 4 zones
(`cidrsubnet` overflowed). No effect on the `plan` of existing
configurations.
## [2.3.0] - 2026-08-30
### Added
- New `nat` variable of object type, with `create` and `per_zone`.
- VPC flow logs **enabled by default**.
⚠️ **Cost**: it adds a log group with 90 days of retention.
Expected plan: `2 to add`.
### Deprecated
- `create_nat`: use `nat.create`. It will be removed in 3.0.0.What makes this CHANGELOG useful where most are not:
- It says what to expect in the
plan.0 to add, 1 to change, 0 to destroyturns the upgrade into something verifiable: if your plan does not match, you stop. - It gives the migration commands, not just a description of the change.
- It flags the cost when there is one.
- It states the upgrade path when you cannot jump directly.
- It distinguishes the three contracts: interface, state and behaviour.
- A module's release flow
flowchart TB
A["Branch off main<br/>feat/nat-per-zone"] --> B["Code change<br/>+ moved if addresses change"]
B --> C["Update examples/<br/>and tests/"]
C --> D["terraform fmt + validate<br/>terraform-docs --output-check"]
D --> E["Apply examples/complete<br/>in a test account"]
E --> F["CHANGELOG entry<br/>with level and expected plan"]
F --> G["Pull request"]
G --> H{"Review:<br/>is the version level<br/>correct?"}
H -- "No: there are address changes<br/>with no moved" --> B
H -- "Yes" --> I["Merge to main"]
I --> J["git tag -a vX.Y.Z"]
J --> K["git push origin vX.Y.Z"]
K --> L["The registry publishes<br/>automatically"]
L --> M["Upgrade dev<br/>and watch for a week"]
M --> N["Upgrade staging"]
N --> O["Upgrade prod"]
style H fill:#fff6e5,stroke:#b7791f
style J fill:#e9f7ef,stroke:#2f855a
style O fill:#e8f0fe,stroke:#1a73e8
The box that really adds value is H, and it deserves an explicit checklist in the repository's PR template:
## Release checklist
- [ ] Has any resource been **renamed**? → `moved` included and tested
- [ ] Has any resource been **removed**? → MAJOR
- [ ] Any new variable **without a `default`**? → MAJOR
- [ ] Any variable **renamed** or removed? → MAJOR (with prior deprecation)
- [ ] Any output renamed or removed? → MAJOR
- [ ] Any `default` changed? → does it cause a replacement? MAJOR; a modification? MINOR
- [ ] Does `required_version` or `required_providers` go up? → review the impact
- [ ] Does it add resources with a **cost**? → highlight it in the CHANGELOG
- [ ] Plan of `examples/complete` attached, with its counts
- [ ] `CHANGELOG.md` updated with the expected plan for consumersAnd the dev → staging → prod staging at the end is not bureaucracy: it is the only way for a bug to be discovered where it does not hurt. Never upgrade a module in all three environments on the same day.
The automation of all this — tagging from the CHANGELOG, publishing, validating the examples on every PR — arrives in module 8.
- Module monorepo versus one repository per module
Monorepo (terraform-modules/) |
One repository per module | |
|---|---|---|
| Structure | modules/network/, modules/data/, modules/app/ |
One repository each |
source |
git::…/terraform-modules.git//modules/network?ref=v2.1.0 |
ecomarket/ecomarket-network/aws or git::…/network.git?ref=v2.1.0 |
| Public registry | Not possible | Yes |
| Versioning | One version for all: tagging bumps everything | Independent per module |
| A change affecting several modules | One single atomic PR | Several coordinated PRs |
| CI | One pipeline; you have to detect what changed | One pipeline per repository, simple |
| Permissions | All or nothing | Per module |
| Discovery | Easy: everything in one place | Needs a catalogue or a registry |
| Version noise | High: app's v2.1.0 may change nothing in app |
None |
The monorepo's problem is the shared version, and it is not a small one: if you tag v2.1.0 because network changed, data's consumers also see a new version that changes nothing for them, and over time they stop reading the CHANGELOGs. There is an in-between solution, prefixed tags:
module "network" {
source = "git::ssh://[email protected]/ecomarket/terraform-modules.git//modules/network?ref=network/v2.1.0"
}It gives independent versioning inside a monorepo, at the cost of a pipeline that knows which prefix to tag depending on what changed. It is what many mid-sized teams do.
The recommendation for EcoMarket, which is also the general criterion:
| Situation | Choose |
|---|---|
| Fewer than 5 modules, a single team | Monorepo with prefixed tags |
| Modules published in the public registry | One repository per module (it is mandatory) |
| Several teams with different permissions | One repository per module |
| Tightly coupled modules that change together | Monorepo |
EcoMarket starts with a monorepo — network, data and app change together while the platform settles — and takes network out into its own repository when it is published in the registry for ecomarket-wholesale. That is a normal path, not a course correction: structure follows need.
- Upgrading to a major version safely
v6.0.0 of terraform-aws-modules/vpc/aws arrives. The procedure has seven steps and none of them is optional.
Step 1: read the CHANGELOG and the migration guide. Before touching anything. Search for the words destroy, replace, recreate, breaking, removed and renamed.
Step 2: check that the constraints are compatible.
If the new version requires aws >= 6.0 and another of your modules asks for ~> 5.8, init will fail with no way out: you have to upgrade both at once or upgrade neither.
Step 3: try it on a branch, in dev only.
$ git checkout -b upgrade-vpc-6
$ sed -i 's/version = "~> 5.8.0"/version = "~> 6.0.0"/' infra/app/main.tf
$ terraform init -upgrade
$ terraform plan -out=plan-v6.tfplanStep 4: analyse the plan thoroughly, in JSON and not by eye.
$ terraform show -json plan-v6.tfplan > plan.json
# What is being destroyed or replaced?
$ jq -r '.resource_changes[]
| select(.change.actions | index("delete"))
| "\(.change.actions | join("+")) \(.address)"' plan.json# Count by action type
$ jq -r '[.resource_changes[].change.actions | join("+")]
| group_by(.) | map({action: .[0], n: length})' plan.json[
{ "action": "create", "n": 4 },
{ "action": "delete+create", "n": 2 },
{ "action": "no-op", "n": 31 },
{ "action": "update", "n": 3 }
]Any delete or delete+create on a stateful resource — a database, a bucket, a volume — is an immediate stop. On stateless resources (a rule, an association) it may be acceptable, but you have to understand why it is happening. This JSON analysis is the same one you will automate as a quality gate in module 8.
Step 5: if there are improper replacements, look for the missing moved blocks. Sometimes the new module renamed resources and did not include moved. You can write them yourself in your configuration, with the module's prefix:
# In YOUR configuration, not in somebody else's module
moved {
from = module.vpc.aws_subnet.private[0]
to = module.vpc.aws_subnet.private["eu-west-1a"]
}And then open an issue on the module asking them to include them: it is a failure of their compatibility contract, not yours.
Step 6: apply in dev and watch. Apply, verify that the application works and wait. A week is reasonable: there are bugs that only appear with a real deployment, a nightly backup or a scale-out.
Step 7: promote through the environments, with days in between.
# Day 1: dev Day 8: staging Day 15: prod
$ terraform init -reconfigure -backend-config=../../backends/prod.hcl
$ terraform init -upgrade
$ terraform plan -out=prod.tfplan # review with the same jq
$ terraform apply prod.tfplanAnd a final warning: do not upgrade several things at once. If you bump the module and the provider in the same PR and something breaks, you will not know which one it was. One change, one plan, one apply.
Common Mistakes and Tips
-
A composition module that also creates resources. Twenty
resourceblocks mixed with fivemoduleblocks is the monolith again. Composition modules orchestrate; leaf modules create. -
Discovering with
datawhat could be injected. It creates dependencies that are invisible to the graph, it fails intermittently on new deployments, it ties the module to your tagging scheme and it makes it impossible to test in isolation. Inject. -
Confusing a module with a separate configuration. Putting
networkinto a module does not reduceplantime or the blast radius: it is still in the same state. For that you need different backends. -
Publishing an internal rename as MINOR without
moved. It is the most destructive mistake in module 4: the interface does not change, theCHANGELOGsays "minor refactor", and the consumer loses their database. The state contract is every bit as binding as the interface one. -
Believing that
movedprevents replacements. It moves addresses, nothing more. If an attribute forcesForceNew, the resource is recreated all the same. -
Using
>= x.y.zwith no upper bound. A MAJOR will come in unreviewed the day somebody runsinit -upgrade. Always~>or a closed range. -
Upgrading all three environments on the same day. It removes the only safety net you have.
devfirst, and wait. -
Tip: the
CHANGELOGshould say what counts to expect in theplan. "Expected plan:2 to add, 0 to change, 0 to destroy" turns the upgrade into something verifiable rather than an act of faith. -
Tip:
terraform show -json+jqto review a big plan. Hunting fordeleteby eye in 600 lines of output does not work. It is also the basis for automated policy checks. -
Tip: save the binary
.tfplanand apply exactly that one.terraform apply plan-v6.tfplanapplies what you reviewed, not what Terraform recomputes half a minute later. In a major upgrade, that difference matters.
Exercises
Exercise 1: classify changes as MAJOR, MINOR or PATCH
For each change to ecomarket-data v1.3.2, state the level, the resulting version and what the CHANGELOG should say:
- A.
maintenance_windowis added withdefault = "sun:04:00-sun:05:00". - B. The
sizevariable is renamed tosizing. - C. The internal resource
local_file.instanceis renamed tolocal_file.main, with amovedblock. - D. The same rename, without
moved. - E. The
defaultofretention_daysgoes from 7 to 14. - F. A
validationis added toengine_versionrequiring PostgreSQL 15 or above (it used to accept 14). - G. The
bucket_arnoutput is added. - H. A typo in a
descriptionis fixed. - I. Mandatory KMS encryption is added to the bucket, which on the real provider forces a replacement.
- J.
required_versiongoes from>= 1.3.0to>= 1.5.0. - K. The module now creates a new
aws_cloudwatch_log_group, enabled by default, with a cost. - L. A
movedblock is added to ease migration for people coming from1.0.0.
Exercise 2: designing a variable's deprecation
ecomarket-network v2.2.0 has create_nat (a boolean) and you want to replace it with a nat object with create and per_zone, without breaking anybody.
- Write the code for
v2.3.0: both variables, thelocalthat decides and thecheckblock that warns. - What version level is
2.3.0? Justify it. - Write the
CHANGELOGentry for2.3.0. - Write the code for
v3.0.0: the removal, with the explanatoryvalidation. - Write the
CHANGELOGentry for3.0.0, with the migration path. - A consumer is on
2.1.0withversion = "~> 2.1". Do they get2.3.0automatically? And3.0.0? What exactly do they see in each case?
Exercise 3: deciding the architecture of a new component
EcoMarket is adding a product search engine: a three-node Elasticsearch cluster, its security group, a snapshots bucket and a function that syncs the catalogue from PostgreSQL every night. It is maintained by the Product team, not the Platform team. The cluster is touched once a quarter; the sync function, twice a week.
- One, two or three modules? Justify it with the five-question rule from 04-01.
- A module inside
infra/appor a separate configuration with its own state? Apply the five criteria from section 5. - If it is a separate configuration, how does it obtain the
vpc_idand the subnets? Write the code and justify the choice against the alternatives. - Draw the resulting mermaid layer diagram, including what already exists.
- The Product team wants to deploy the sync function several times a week without waiting for Platform. What does that imply for the architecture and for permissions?
Solutions
Solution 1
| Case | Level | Version | What the CHANGELOG should say |
|---|---|---|---|
| A | MINOR | 1.4.0 |
"Added: maintenance_window (default sun:04:00-sun:05:00). Expected plan: 0 to change if unused" |
| B | MAJOR | 2.0.0 |
"⚠️ BREAKING: size renamed to sizing. Every consumer must update the call." The right thing would have been a prior deprecation in 1.4.0 |
| C | MINOR | 1.4.0 |
"Changed: internal resource renamed to main. Includes moved, transparent migration. Expected plan: has moved to, 0 to destroy" |
| D | MAJOR | 2.0.0 |
"⚠️ BREAKING: internal resource renamed without moved. It destroys and recreates the database. DO NOT APPLY without a migration plan." In practice this should not be published: add the moved and publish it as MINOR |
| E | MINOR | 1.4.0 |
"Changed: retention_days default 7 → 14. Only affects those who do not specify it. Expected plan: 1 to change (in-place modification, no replacement)" |
| F | MAJOR | 2.0.0 |
"⚠️ BREAKING: engine_version now requires PostgreSQL ≥ 15. Anybody on 14 will get a validation error" |
| G | MINOR | 1.4.0 |
"Added: bucket_arn output" |
| H | PATCH | 1.3.3 |
"Documentation: fixed a typo in the description of size" |
| I | MAJOR | 2.0.0 |
"⚠️ BREAKING: mandatory KMS encryption. It forces the bucket to be replaced: objects are NOT migrated. Requires copying the data manually before applying" |
| J | MAJOR | 2.0.0 |
"⚠️ BREAKING: requires Terraform ≥ 1.5.0 (check blocks are used)" |
| K | MINOR | 1.4.0 |
"Added: log group enabled by default. ⚠️ Extra cost. Expected plan: 1 to add. Can be switched off with logs = false" |
| L | PATCH | 1.3.3 |
"Added: moved blocks for migrations from 1.0.0. No effect if you are already on 1.3.x" |
Cases C and D are the same code change with two different version levels. The difference is five lines of moved, and it is the reason the PR checklist asks explicitly about renames.
Case I deserves a comment: it is a change that improves security and still destroys data. A responsible module does not simply publish it as MAJOR; it adds a transition variable (kms_encryption = optional(string, null)) that lets each consumer migrate when they can, and leaves mandatory encryption for a later MAJOR, once everybody has migrated.
Solution 2
Point 1 — code for v2.3.0:
# variables.tf
variable "create_nat" {
description = "DEPRECATED since v2.3.0: use 'nat = { create = ... }'. It will be removed in v3.0.0."
type = bool
default = null
}
variable "nat" {
description = "Configuration of the NAT gateway for internet egress."
type = object({
create = optional(bool, true)
per_zone = optional(bool, false)
})
default = {}
}
# locals.tf
locals {
# The old variable takes priority if it was used: that way, anybody who has
# not migrated keeps EXACTLY the previous behaviour.
nat = {
create = var.create_nat != null ? var.create_nat : var.nat.create
per_zone = var.nat.per_zone
}
}
# checks.tf
check "create_nat_deprecated" {
assert {
condition = var.create_nat == null
error_message = <<-EOT
DEPRECATION WARNING: the 'create_nat' variable has been deprecated since
v2.3.0 and will be removed in v3.0.0 of ecomarket-network.
Replace: create_nat = ${var.create_nat}
With: nat = { create = ${var.create_nat} }
See CHANGELOG.md, section [2.3.0].
EOT
}
}
# main.tf
resource "local_file" "nat" {
count = local.nat.create ? (local.nat.per_zone ? length(var.zones) : 1) : 0
# ...
}Point 2 — it is MINOR (2.3.0). Functionality is added and nothing stops working: whoever used create_nat gets the same plan as before, and whoever did not use it notices nothing either. The check block produces a warning, not an error, so it breaks neither the plan nor the apply.
Point 3 — CHANGELOG for 2.3.0:
## [2.3.0] - 2026-10-02
### Added
- New `nat` variable of object type, with `create` (bool, default `true`)
and `per_zone` (bool, default `false`). `per_zone = true` creates one NAT
gateway per availability zone: higher availability, higher cost.
### Deprecated
- `create_nat` is now deprecated. Replace it with `nat = { create = ... }`.
It will keep working throughout the 2.x series and **will be removed in 3.0.0**.
The `plan` will show a warning while you carry on using it.
### Notes
- Transparent upgrade: `0 to add, 0 to change, 0 to destroy` if you change
nothing in your call.
- Requires Terraform >= 1.5.0 because of the use of `check` blocks.Point 4 — code for v3.0.0:
variable "create_nat" {
description = "REMOVED in v3.0.0. Use 'nat = { create = ... }'."
type = bool
default = null
validation {
condition = var.create_nat == null
error_message = <<-EOT
The 'create_nat' variable was removed in ecomarket-network v3.0.0.
Replace: create_nat = true
With: nat = { create = true }
If you need to upgrade gradually, pin version = "~> 2.9" and migrate
the call before moving to 3.x.
EOT
}
}
locals {
nat = var.nat # there is no fallback any more
}The variable is kept only in order to give a comprehensible error; without it, the consumer would get an Unsupported argument that does not say what to use instead. In 3.1.0 it can be removed entirely.
Point 5 — CHANGELOG for 3.0.0:
## [3.0.0] - 2026-12-01
### ⚠️ Breaking changes
- **Removed the `create_nat` variable** (deprecated since 2.3.0).
Use `nat = { create = ... }`.
- **Removed the 2.x series `moved` blocks.** If you are coming from a
version earlier than 2.9.0, upgrade to 2.9.x first and apply.
### How to migrate
1. Pin `version = "~> 2.9"` and run `terraform init -upgrade && terraform apply`.
2. Change the call:
- `create_nat = true`
+ `nat = { create = true }`
3. Run `plan`: it must come out at `0 to add, 0 to change, 0 to destroy`.
4. Move up to `version = "~> 3.0.0"`, run `init -upgrade` and `plan`.
5. **If any `to destroy` appears, do not apply and open an issue.**Point 6 — the consumer on 2.1.0 with ~> 2.1:
| Version | Do they get it? | What they see |
|---|---|---|
2.3.0 |
Yes: ~> 2.1 accepts any 2.x |
On running init -upgrade, a warning in the plan about create_nat. The plan stays at zero and everything works |
3.0.0 |
No: ~> 2.1 excludes 3.0.0 |
Nothing. They stay on the latest 2.x, which is exactly the desired behaviour |
This is the value of the pessimistic operator: breaking changes never arrive on their own. The consumer migrates when they decide, by editing their version, and meanwhile the warning reminds them on every plan that there is work pending. Note also that 2.3.0 requires Terraform ≥ 1.5.0 because of the check blocks; EcoMarket uses 1.9.8 according to its .terraform-version, so there is no problem, but it is the kind of detail that must be in the CHANGELOG.
Solution 3
Point 1 — two modules.
| Candidate | Does it repeat? | Does it encapsulate a decision? | Own name? | Short interface? | Tested in isolation? | Verdict |
|---|---|---|---|---|---|---|
search (cluster + SG + snapshots bucket) |
Yes (dev/staging/prod) | Yes: sizing, encryption, retention | Yes: "the search" | Yes: ~6 variables | Yes | Module |
sync (function + permissions + schedule) |
Yes | Yes: retries, window, alerts | Yes: "the synchroniser" | Yes: ~5 variables | Yes, with fake endpoints | Module |
| All together | — | — | No | No | No | Monolith |
Two modules and not one, on the rate of change criterion: the cluster changes quarterly and the function twice a week. Merging them would force you to publish a cluster version every time a timeout is touched. And not three, because the security group and the snapshots bucket have no life of their own: they exist for the cluster and they are destroyed with it.
Point 2 — a separate configuration.
| Criterion | Analysis | Conclusion |
|---|---|---|
| Rate of change | Twice a week versus app's weekly |
Similar, it does not decide |
| Blast radius | A failure deploying the sync must not be able to touch PostgreSQL or the front end | Separate |
| Permissions | It is maintained by Product, not Platform | Separate: this is the decisive criterion |
apply duration |
An Elasticsearch cluster takes 15-25 minutes to create | Separate: it cannot be added to every app apply |
| Organisational boundary | Different teams | Separate |
Four out of five criteria in favour. A separate configuration:
ecomarket-infra/infra/search/ ├── main.tf (calls modules/search and modules/sync) ├── variables.tf ├── outputs.tf ├── versions.tf └── backend.hcl
Point 3 — obtaining the network:
# infra/search/main.tf
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "ecomarket-tfstate"
key = "ecomarket/${var.environment}/network/terraform.tfstate"
region = "eu-west-1"
}
}
module "search" {
source = "ecomarket/ecomarket-search/aws"
version = "~> 1.0.0"
base_name = local.prefix
vpc_id = data.terraform_remote_state.network.outputs.vpc_id
subnets = data.terraform_remote_state.network.outputs.private_subnets
size = local.current.search_size
tags = local.common_tags
}Justification against the alternatives:
| Alternative | Why not |
|---|---|
Provider data sources (data "aws_vpc" by tag) |
It couples to the tagging scheme and fails with an uninformative error if somebody changes a tag |
A parameter store (/ecomarket/<environment>/network/vpc_id) |
It is better if Product must not be able to read network's state. See the caveat below |
Variables in search's .tfvars |
It duplicates identifiers that already exist; they go out of sync when the network is recreated |
The important caveat: terraform_remote_state gives Product read permission on network's entire state. If network contains no secrets — and it should not — that is acceptable inside the same company and the same repository. If the security team vetoes it, the right alternative is for network to publish vpc_id and private_subnets into the parameter store and for search to read them from there, as already discussed in 03-03. And in both cases, the search module does not change: it receives vpc_id and subnets by injection, and it does not care where they come from.
Point 4 — diagram:
flowchart TB
subgraph ST["Independent states"]
S1[("ecomarket/<e>/network")]
S2[("ecomarket/<e>/app")]
S3[("ecomarket/<e>/search")]
end
subgraph CFG["Root configurations"]
CN["infra/network<br/><i>Platform team</i>"]
CA["infra/app<br/><i>Platform team</i>"]
CS["infra/search<br/><i>Product team</i>"]
end
subgraph MOD["Published modules"]
MN["ecomarket-network v2.x"]
MD["ecomarket-data v1.x"]
MA["ecomarket-app v3.x"]
MB["ecomarket-search v1.x"]
MS["ecomarket-sync v1.x"]
end
CN --> MN
CA --> MD
CA --> MA
CS --> MB
CS --> MS
CN --- S1
CA --- S2
CS --- S3
S1 -.->|"terraform_remote_state<br/>vpc_id, subnets"| CA
S1 -.->|"terraform_remote_state<br/>vpc_id, subnets"| CS
S2 -.->|"db_endpoint"| CS
style CS fill:#f3e8fd,stroke:#7c3aed
style MB fill:#f3e8fd,stroke:#7c3aed
style MS fill:#f3e8fd,stroke:#7c3aed
Point 5 — Product's autonomy. It implies four concrete things:
- Its own pipeline for
infra/search, with its own approval, not depending on Platform's deployment queue. - Its own IAM role, with permissions on Elasticsearch, Lambda and its bucket, and read-only on
network's state. No write permission on the VPC, the database or the front end. - Independent locking: Product can apply while Platform applies
app, because they are different states. This on its own justifies the separation. - An explicit contract about
network's andapp's outputs. The momentsearchreadsvpc_idanddb_endpoint, those outputs become a public API between teams: renaming them breaks the other team'splan, and the error shows up far from where the change was made. There must be a written agreement that those outputs will not be changed without notice and without a transition period — exactly the same versioning discipline you apply to modules, now between configurations.
If on top of that the sync function came to be deployed several times a day, the natural next step would be to separate it from search into its own configuration too, on the apply duration criterion: nobody wants to wait for an Elasticsearch cluster to refresh in order to update a function.
Conclusion
With this lesson you close module 4 and EcoMarket stops having a main.tf that does too much:
- In Terraform there is no inheritance, only composition: what is not in the interface cannot be changed from outside. What is missing gets added outside the module, building on its outputs.
- Modules split into leaf ones (they create resources, highly reusable, strict versioning) and composition ones (they orchestrate modules, a business interface, specific to the organisation). A composition module that creates twenty resources is a monolith in disguise.
ecomarket-platformtranslates intent into technique: two variables,base_nameandprofile, instead of thirty, with the profile table inside. An environment's configuration comes down to six arguments and one output.- Inject, do not discover. Passing the
vpc_idas a variable creates the edge in the graph, guarantees the ordering, decouples from the tagging scheme, allows isolated testing and requires no extra permissions.dataonly for what is genuinely external. - A module organises code; only a separate configuration organises state. You separate on rate of change, blast radius, permissions,
applyduration and organisational boundary; and the bridge isterraform_remote_state, with the warning that it grants access to the entire state. - An infrastructure module has three contracts: interface (variables and outputs), state (the resources' addresses) and behaviour (what the
planproduces). The second is invisible in the consumer's code and it is the one that destroys databases. - The classification table settles the borderline cases, and the most instructive one is the internal rename: with
movedit is MINOR, withoutmovedit is MAJOR and destructive. Five lines separate one from the other. - Consumers pin
~> 2.1.0inprodand~> 2.1indev, never>=with no bound, remembering that there is no module lock file. movedinside the module is its compatibility contract: addresses relative to the module, commented by version, kept until the next MAJOR and cleaned up only then. It does not prevent replacements, only address changes.- Deprecated variables are simulated by keeping both for one more version, with a
checkblock that warns without breaking, and an explanatoryvalidationwhen they are finally removed. - A useful
CHANGELOG.mdsays what counts to expect in the plan, gives the migration commands, flags the costs and lays out the upgrade path; and the release flow — branch, examples, tests, reviewing the version level, tag,dev→staging→prodwith days in between — is what keeps it honest. - Monorepo with prefixed tags while the modules change together; one repository per module when you have to publish to the registry or separate permissions. Going from one to the other is a normal path, not a mistake.
- And a major upgrade is done by reading the
CHANGELOG, checking the provider constraints, trying it on a branch indev, analysing the plan withterraform show -jsonandjqto hunt down anydelete, writing yourself themovedblocks the third-party module forgot, and promoting through the environments with days in between.
In this module EcoMarket has travelled the whole road: from a 340-line main.tf duplicated by copy and paste, to a platform of versioned, documented, published modules composed in layers, where every decision lives in a single place and refactoring costs not one destruction. And now comes what we have been postponing for four modules. Everything you have built — the network, the data, the application — is still JSON files generated by the local provider: simulated infrastructure, perfect for learning the language without paying a bill, but it does not serve a single order. In module 5, Resource Provisioning, EcoMarket finally goes to the cloud: you will start with the Provisioning Basics — credentials, regions, the real life cycle of a resource that takes twenty minutes to create and the differences between what is simulated and what is billed — and you will go on to really deploy the VPC, PostgreSQL and the images bucket on AWS, their equivalents on Azure and GCP, and the configuration of the servers with user_data, cloud-init and provisioners. The modules you have just written are exactly the ones you are going to use: you will swap local_file for aws_vpc, aws_db_instance and aws_s3_bucket, and you will see that the interface, the locals, the tagging and the versioning all still hold as they are. That, and not the JSON files, is what you have been building.
