Composition over nesting, and for_each on modules
Keep the module tree flat and pass dependencies in, then call a module once per item with for_each and read why keys, not counts, keep addresses stable.
Composition over nesting, and for_each on modules
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Terraform's docs recommend a flat module tree with one level of child modules. The root module connects them with expressions such as `vpc_id = module.network.vpc_id`. That is composition.
- A module that receives the things it depends on, instead of creating its own copy, is easier to reuse and to refactor. The docs call this dependency inversion.
- Deep nesting hides what a module needs, makes provider passing awkward, and lengthens every resource address. Reach for a second level only when a module is truly an internal part of another.
- `count`, `for_each` and `depends_on` work on `module` blocks. Prefer `for_each` over a set or map, so each instance is addressed by a key such as `module.bucket["notes"]` and removing one touches only that one.
- A module that contains its own `provider` block cannot be used with `for_each`, `count` or `depends_on`.
The module that builds the world
Someone writes an app module that creates a VPC, subnets, a cluster and a database, because that is what an app needs. It works. Then a second team wants the app in an existing VPC. A third wants two apps sharing one database. The module can’t do either, because it created its own network and database inside, and nothing outside can reach in. The cure is a rule of thumb from the Terraform docs: keep modules small, and pass in what they depend on.
Composition: a flat tree
The docs describe two shapes. With only a root module, resources form a flat set linked by expressions. Introducing module blocks makes it hierarchical, and each module may have child modules, “which can potentially create a deep, complex tree”. They then say that in most cases they strongly recommend keeping the module tree flat, with one level of child modules, and linking the modules with expressions, as the resources were. They call this flat style module composition. This is their example, which I cannot run here:
module "network" {
source = "./modules/aws-network"
base_cidr_block = "10.0.0.0/8"
}
module "consul_cluster" {
source = "./modules/aws-consul-cluster"
vpc_id = module.network.vpc_id
subnet_ids = module.network.subnet_ids
}
The root module is the only place that knows consul_cluster runs inside network. That gives you the dependency inversion the docs describe: instead of a module embedding its dependencies and managing its own copy, it receives them from the root, which can connect the same modules in different ways. The cluster module does not care whether the VPC ID came from a module, a data source or a variable. A later refactor that moves the network into its own configuration only changes the root.
The docs make the same argument for conditional creation. If a module needs a thing that exists in some environments and not others, do not make the module detect and create it. Make it accept the object as an input, and let the root decide.
Why deep nesting hurts
A module tree three levels deep has several costs.
- Hidden requirements. A grandchild needs a subnet ID, so every module in between needs a variable only to pass it along.
- Long addresses.
module.app.module.db.module.network.aws_subnet.private["a"]is state you have to type instate mv,movedandimportcommands. - Provider plumbing. Provider configurations live in the root and are passed down, by inheritance or the
providersargument. More levels mean more places for it to go wrong. - Blast radius. A change near the bottom ripples through plans of everything above it.
Nesting is not wrong. A module with a private helper that no caller should use, such as a policy builder, can reasonably wrap it. But if a caller might want the inner module on its own, it belongs at the root level beside its sibling.
for_each on modules
When you need the same module several times, call it once with for_each. count, for_each and depends_on have worked on module blocks since Terraform 0.13.
variable "teams" {
type = set(string)
}
module "bucket" {
source = "./modules/bucket"
for_each = var.teams
name = "acme-${each.key}"
}
output "bucket_arns" {
value = { for team, m in module.bucket : team => m.arn }
}
Written from the language docs and not run. Each instance gets its own address, module.bucket["notes"], its outputs are read by key, and the for expression turns them into a map. Provider rules apply: the docs say a module that contains its own provider configurations is not compatible with for_each, count or depends_on, one more reason to keep provider blocks out of reusable modules.
Keys, not positions
I used my toy planner again to compare count and for_each over three teams when the middle team, notes, is removed. It is a Python stand-in that compares addresses and one attribute. Its labels are mine, and it prints a bucket rename as an update, though a real bucket name change is a replacement.
module with count, remove 'notes' from ['billing', 'notes', 'search']:
~ update module.bucket[1].aws_s3_bucket.this: {'bucket': 'acme-notes'} -> {'bucket': 'acme-search'}
- destroy module.bucket[2].aws_s3_bucket.this
module with for_each, remove 'notes' from ['billing', 'notes', 'search']:
- destroy module.bucket["notes"].aws_s3_bucket.this
With count, the list shifts, so index 1 turns from notes into search, and the last index is destroyed. That is the wrong bucket changing. With for_each, the key notes is the identity, and only it is removed. Use for_each over a set or map for module instances. Reserve count for an on-or-off switch such as count = var.enabled ? 1 : 0.
About the video
The embed is “Meet the experts: Terraform module design”, a HashiCorp panel published November 2024, 30 minutes, with Ned Bellavance, Drew Mullen and Bruno Schaatsbergen. Its description says the panel discusses best practices, design patterns and lessons learned for module design. I judged it from that description and the speakers only. It has no chapters, and I cannot say it covers for_each on modules, which this lesson adds from the docs. Two other talks are in deeper. Yevgeniy Brikman’s October 2017 talk on composable modules predates Terraform 0.13, so its syntax and its lack of for_each on modules are out of date, though its argument for small composable pieces still reads well. The 2026 Minecraft talk uses a provider to teach cohesion and composition, from a tiny audience. English was judged from the title, description and the English auto-caption track of each.
Where this fits
You now have modules that compose and repeat. The last lesson in this group is about making them usable by people who didn’t write them: documenting and publishing modules.
Check yourself
Why does the root module pass `vpc_id` to a Consul module instead of the Consul module creating its own network?
The module stays small and can sit in any network, including an existing one found with a data source. The caller decides how the ID is obtained. That is dependency inversion, as the docs describe it.
You call a module with `count = 3` over a list of team names and remove the middle name. What happens?
The instances are addressed by position, so `[1]` now refers to what was `[2]`. The plan updates or replaces the second instance and destroys the third, instead of just removing the middle one.
Where do you read one instance's output from a module called with `for_each`?
By key, as `module.bucket["notes"].arn`. To collect all of them, use a `for` expression: `{ for k, m in module.bucket : k => m.arn }`.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.