Map Teams and Trust Boundaries Before Drawing Folders
The argument usually starts with a folder name. A platform team of six supports forty application engineers, the shared root now takes forty minutes to plan, and a one-line DNS fix waited three hours behind a database replacement last Friday. Someone proposes a tidier tree — one folder each for network, data and services under prod. The proposal is reasonable, and on its own it changes nothing.
A folder is a label, not a boundary
Terraform does not read directory names as permissions. A directory called prod is a label; a credential that can write prod is a boundary. Decide what must not fail together, then name the directories after the decision.
Think of fire compartments in a building. The walls go up before the rooms are named, and naming a room "fireproof" does not slow a fire. Infrastructure boundaries work the same way: the compartment is decided by construction, not by the label.
Four levels have to be separated before any of that naming makes sense. Each answers a different question, and only the last one becomes a directory.
| Level | It decides | Concretely |
|---|---|---|
| Organization | Identity, policy and billing ceiling | An AWS Organizations root and its organizational units, an Azure tenant with management groups, a GCP organization with folders. SCPs, Azure Policy assignments and organization policy constraints apply to everything underneath; nobody applies Terraform here as a routine act. |
| Account, subscription or project | The credential boundary | The only level that survives a stolen key, because a principal in one account cannot read another account's resources without an explicit trust relationship. Decided first, because no amount of naming can imitate it. |
| Environment | Risk appetite plus approval regime | Dev is disposable with no approval and synthetic data; staging is production-shaped with one reviewer and no customer records; production takes two approvals, a change window, a tested rollback and a break-glass path. A property of an account and a pipeline, not a word in a path. |
| Component | The deployable unit | Network, data, service or edge, each with its own lifecycle, failure modes and usually its own on-call rotation. |
A workable default is one account per environment per business unit, plus a shared platform account for state, DNS and identity. Some organizations collapse staging and production into one account with separate roots. That is a real trade-off — fewer accounts to administer, weaker isolation — and it should be written down as an exception with an owner, not discovered later during an incident.
Figure 1 orders the questions the way a review should ask them. Policy sets the ceiling, identity decides who can act, environment decides how much ceremony surrounds the act, and only then does the component decide how many roots there are.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
Q["New resource or change"] --> O["Organization policy
SCPs, Azure Policy, org policy"]
O --> A{"Which credential
can change it?"}
A -- "shared platform" --> P["Platform account
state, bootstrap, DNS zone"]
A -- "one product, one environment" --> E{"Which environment
owns the risk?"}
E -- "dev" --> D["dev account
no approval, disposable"]
E -- "stage" --> S["stage account
peer review, prod-shaped"]
E -- "prod" --> R["prod account
two approvals, change window"]
D --> C{"Same lifecycle and
on-call as its neighbours?"}
S --> C
R --> C
P --> C
C -- "yes" --> T["One root module"]
C -- "no" --> U["Separate roots
network, data, service"]
T --> V["One state, one lock,
one plan, one apply"]
U --> V
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class Q,O,R primary;
class P,D,S,T,U secondary;
class A,E,C warn;
class V ok;
The layering is easier to hold onto as a containment picture than as a checklist. Figure 2 shows one organization, two accounts, one environment band and three component roots inside it. Read it outward-in: the organization encloses everything, the account is the line a stolen credential cannot cross, the environment band is where approval rules live, and only the innermost boxes are directories in a repository.
A Root Module Is an Independently Applied Change Unit
A root module is the directory you initialize, plan and apply. That definition sounds mechanical, and it is exactly why it matters: the root is the unit that owns one state object, one lock, one set of provider configurations, one plan, one apply and one set of approvers. Everything in it shares a fate. If you cannot describe a change as "one plan, one review, one apply window", you have put more than one change unit in the same root.
That makes the root boundary a question about lifecycle, not about which resources reference each other. Three roots cover most estates.
A network root owns VPCs or VNets, subnets, route tables, firewall rules, NAT gateways and private DNS zones. It changes quarterly, its plans take minutes, and almost everything else depends on it. Its outputs — subnet IDs, CIDR blocks, zone IDs — are the most widely consumed values in the estate, so they need a published contract. Removal is rare and usually blocked by a prevent_destroy lifecycle rule or by policy, because deleting a VPC deletes what is inside it.
A data root owns databases, buckets, key management keys, retention policies and snapshots. It changes monthly, its plans are slow because replacement is expensive, and its state carries the most sensitive attributes. Access to that state should be narrower than access to the service root's state, and plan approval should include someone who understands the data, not just the infrastructure.
A service root owns compute, containers, queues, autoscaling and the workload's own IAM. It changes several times a day, its plans are short, and destroying it should be routine — that is what preview environments are. Fast, frequent and recoverable is the point.
An edge or DNS root owns certificates, CDN configuration and public records. It sits beside the service root because certificate validation and the record that proves it are one lifecycle, as the earlier provider article showed.
Figure 3 compares the three main roots along the axis that decides the split: how long a change lives and how bad its worst case is.
Four tests, one split
Two resources belong in the same root only when all four hold: the same credential scope, the same lifecycle, the same on-call, and one reviewer can meaningfully judge the whole plan. A "no" on any one is a split, even when the resources obviously talk to each other.
The instinct to merge usually comes from a legitimate worry: splitting means passing values across an apply boundary, and that is work. Figure 4 shows where that work lands, and where the split pays for itself. A change either fits one root's lifecycle or it does not; when it does not, the plan becomes an ordered sequence with a published value between the steps.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Change request
service needs a new database"] --> B{"Same credential, lifecycle
and on-call as neighbours?"}
B -- "no" --> C["Split: data root
and service root"]
B -- "yes" --> D["One root, one plan"]
C --> E["Plan data root first"]
E --> F{"Create or in-place
update only?"}
F -- "no, replacement" --> G["Stop: replacement in
a protected root"]
F -- "yes" --> H["Apply data root,
publish endpoint"]
H --> I["Plan service root
with the published value"]
D --> J["Single plan,
single apply"]
I --> K{"Both roots no-op
after the apply?"}
J --> K
K -- "no" --> L["Drift or a missed
consumer: investigate"]
K -- "yes" --> M["Change complete,
contract verified"]
G --> N["Rehearse with import
or a snapshot restore first"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,E,H,M primary;
class B,D,I,J,K,L secondary;
class C,N warn;
class F,G danger;
The usable middle
A root that is too large produces lock contention, mixed plans, partial applies and a plan nobody can review. A root that is too small produces hundreds of state files, long chains of manual hand-offs, and changes that can never be atomic. Aim for a root you can plan in under about ten minutes, whose diff one owner can read, and whose failure takes down one thing.
CLI workspaces do not solve this. As the backend article showed, workspaces in one working directory share a backend, a set of credentials and a provider configuration; selecting prod is one flag away from selecting dev. Workspaces suit short-lived review environments, not production isolation.
Choose Monorepo or Multirepo for Real Ownership Needs
The repository question is downstream of the root question. Once you know how many roots you have and who owns them, the repository question is about review flow and pipeline identity — not about Terraform's behavior. A single state file does not care which repository its configuration came from, and splitting repositories does not split state. Teams that move to a new repo and keep one root discover this the expensive way.
A monorepo holds many roots and the shared modules they consume in one repository. A multirepo gives each root, or each team's set of roots, its own repository, with shared modules published as versioned releases. A hybrid — one platform repository for modules, bootstrap and shared network, plus one repository per product team — is what most organizations converge on, because it splits the two things that change at different speeds.
The table below compares the two extremes on the dimensions that actually change behavior.
| Dimension | Monorepo | Multirepo | Decide by |
|---|---|---|---|
| Review boundary | One pull request shows the module change beside every root that consumes it; CODEOWNERS routes approval by path | A cross-repo change needs two pull requests, a merge order and two approvals; each repo has one clear owner | Whether reviewers need the module diff and the root diff in one place |
| Shared modules | Live in modules/, with roots under environments/ or live/, consumed by relative path; a breaking change is one commit and one pipeline run | Published as tagged releases; consumers pin a constraint and upgrade deliberately | How often the shared code changes and how many consumers must move together |
| Release cadence | Any merge can reach any root; path filters and per-root environments decide what applies, so a bad filter is the main risk | A release or tag triggers one root's pipeline; cadence is genuinely independent per team | Whether teams ship on different schedules for real reasons |
| Pipeline scope | One CI configuration and usually one credential broker; per-root jobs need per-root identities to be meaningful | One pipeline per repo, with OIDC trust bound to that repository; compromise reaches one root | The credential blast radius you can tolerate |
| Inventory | find over the tree is the inventory; complete, but easy to miss a root nobody has touched | The inventory lives in a catalog, a topic list or a repository naming convention that must be maintained | Whether a service catalog already exists |
| Refactor cost | Moving a directory and its state is one reviewed change | Moving a root means a new repo, new CI identity, new state key and a migration window | Whether boundaries are still settling |
| Visibility | Read access to the repo exposes every root's configuration, including account IDs in backend files | Repository permission is the first gate; state access is granted separately | Contractors, partners or regulated audit scopes |
| Best fit | A platform team owning modules and many small roots, or an organization whose boundaries are still moving | Teams with independent budgets, independent audit scope and stable boundaries | Who is accountable when a root breaks |
Read the table as a set of trade-offs, not a ranking. The monorepo's real advantage is atomic refactoring: renaming a module input and updating twelve roots in one reviewed commit is a genuinely safer operation than coordinating twelve repositories.
Repository permission is not a security boundary
A single CI identity that can apply every root means a compromised pipeline reaches every environment, no matter how neatly the directories are arranged.
The multirepo's advantage is that the boundary is visible in the permission system: the production root's repository has its own OIDC trust, its own approvers and its own audit trail. Its cost is version skew. Six months after the split, three teams run ~> 2.4, two run ~> 2.9 and one has a fork with a patch that never went upstream. Nothing is broken, and nobody can say which behavior is current.
Three practices keep either choice honest. Path-filtered pipelines need a test that proves a change to environments/prod cannot trigger the development apply. Every root needs a named owner in a file next to it, not only in a wiki. And shared modules need a compatibility policy — additive inputs, deprecation windows, and a changelog — because that policy is what makes multirepo survivable.
One anti-pattern deserves naming: using -target as a segmentation strategy. terraform plan -target=module.service is a debugging aid for a broken state or a partial recovery. It does not create a boundary, it does not prevent the rest of the root from being planned later, and a habit of targeting is a signal that the root contains more than one change unit.
Share Data Without Reading Every Team’s State
Splitting roots creates a new problem immediately. The service root needs the subnet IDs that the network root creates, and the application needs the database endpoint that the data root publishes. The convenient answer is terraform_remote_state. The correct answer depends on who is asking.
A remote-state read is wider than the output you wanted. As covered earlier in the series, the data source reads the producer's entire state snapshot and then exposes the requested outputs. The permission required is GetObject on the whole state object, not on one output. A consumer in another team therefore receives read access to every attribute the producer manages, including values that were never outputs and values providers marked sensitive. That is a data-sharing decision disguised as a convenience.
Three patterns are available, in increasing order of isolation.
| Pattern | What the consumer reads | Permission granted | Use when |
|---|---|---|---|
| Published values | One intentional value from an SSM parameter, an S3 object under a dedicated prefix, a DNS record, a Kubernetes ConfigMap or a service-catalog entry | Scoped to that path; the value is visible in a plan and the producer's state stays unread | A few values cross a team boundary and a narrow read is enough |
| Documented remote-state contract | The producer's outputs, read through terraform_remote_state | GetObject on the specific key; never ListBucket on the bucket, never write access | Inside one trust domain — same team, same account, same on-call — especially when many values are needed. Write the contract down: producer key, consumer root, outputs consumed, role used, approver and review date. A short table in the platform repository turns an invisible permission into an accountable one. |
| Control-plane outputs | tfe_outputs reads workspace outputs through the HCP Terraform API rather than the state object | Token permission on that workspace; values is marked sensitive and nonsensitive_values carries the safe subset | Cross-workspace reads where you want an interface rather than a state snapshot, with output hygiene still deciding what leaks |
Publish with a managed resource so the write happens in the same apply, or with terraform output -json in CI when the store sits outside Terraform's control.
Whichever path you choose, the interface needs a version and an owner. Name the output for what it means (private_subnet_ids, not output1), state its type, and give it a deprecation path. A removed output should fail a contract test in the producer's pipeline, not a consumer's plan during an incident.
Runtime discovery is the other half. A service that needs the database endpoint at boot should read it from SSM, a secret manager or DNS — not from a Terraform state file. Terraform is how the value gets published; it should not be in the request path of the application.
Bootstrap New Environments Without Copy-Paste Sprawl
The most common way to add staging is to copy environments/dev to environments/stage and edit until it plans. It works for a quarter. Then the two directories diverge: a security group rule added to dev and forgotten in stage, a provider version bumped in one place, a subnet CIDR that overlaps because nobody re-read the other file. Six months later there are four variants, a fix lands in three, and nobody can say which differences are intentional.
The alternative is a thin root per environment that composes versioned modules and supplies explicit values. The root stays small — often under a hundred lines — because the resources live in modules and the environment differences live in values. Figure 5 contrasts the two shapes.
The discipline is in what the root is allowed to contain. It declares a partial backend, one provider configuration with an account guard and an assumed role, and module calls with pinned version constraints. Everything environment-specific is a typed variable with a validation, supplied by an env.tfvars file or by the pipeline. Conditional sprawl inside modules — count = var.environment == "prod" ? 3 : 1 repeated in twenty resources — is how a module becomes unreadable; a small number of well-named inputs is easier to review and test.
Bootstrapping order matters as much as shape. The backend must exist before the first root points at it, which is why the state bucket belongs to a separate bootstrap root, as covered in the backend article. After that, network is applied before data and services, because it publishes the values they consume. Each environment repeats that order independently, so a broken staging apply never blocks a production fix.
Two guardrails prevent the sprawl from returning. First, a repository check that fails when a root contains more than a threshold number of resources or when an environment directory calls a module without a version constraint. Second, a promotion rule: the same module version is applied to staging before production, and the production pull request references the staging apply. Neither is a Terraform feature; both are cheap pipeline code that keeps the thin-root pattern from decaying back into copies.
Migrate a Large Root in Rehearsed Steps
Every organization with a giant root has a story about the Friday it became urgent. The migration is not a refactor; it is an ownership transfer of live objects, and it deserves the same treatment as a production change: a plan, a freeze window, a backup, a rehearsal and an independent check.
Start by measuring, not by drawing the target tree. Count resources per module, read the git history for change frequency by path, record how often a plan waits on the lock, and note who approves which directory today. The paths that change weekly are the ones that want their own root. The output is a table: current address prefix, target root, owner, approver and apply order. That table is also the lab's evidence.
Then carve along ownership and lifecycle. A root that contains the VPC, the database and six services splits into three roots, and the service roots may split again by team. Resist carving by resource type alone: a "compute root" that mixes four teams' services has the same review problem as the original. The test from earlier still applies — same credential, lifecycle, on-call and review.
The mechanics have two shapes, and picking the wrong one is how migrations turn into recreation events.
Pick the shape before you touch state. Within one state, terraform state mv moves the address and the object record together, so nothing is destroyed or imported. Across states, the reviewed pair of blocks above is the safer shape: an import block is plan-visible, and a plan that proposes replacing a database is a stop signal rather than a detail.
Order matters more than either command. Freeze applies in both roots, then import into the target and confirm the plan adopts every object without replacement. Apply that import. Verify a no-op plan in the target. Only then apply the removed blocks in the source, and verify that the source plans no destroys. During the overlap both states list the same objects, which is safe only because nobody is applying; that is exactly what the freeze window buys.
Never force-unlock during a migration
The migration writes state, so it takes the lock. Set -lock-timeout=10m so a routine migration waits instead of failing, and check the lock holder before anything else. The lock is the only thing preventing a teammate's queued apply from writing the old address map after you have moved it.
Back up before the first write, not after the first failure. terraform state pull into an encrypted location, checksum it, and record the lineage and serial for both source and target. A backup whose lineage you did not record cannot prove which state it came from, and a backup left in a downloads folder is a second copy of every secret in the root.
Verification is independent of the migration tool. Compare resource counts between the old state list and the new one. Run terraform plan -detailed-exitcode in each root and require exit code 0. Spot-check the objects that would be expensive to recreate — the database, the KMS key, the bucket policy — with terraform state show. Check the provider identity output to prove each root reached the intended account. And read the cloud audit log for delete events in the migration window; there should be none. A migration that "looked fine" but logged a delete is a migration with a restore ahead of it.
Retire the old root deliberately: remove it from the pipeline, archive the backup under the retention policy, delete the directory, and record the new ownership table. Then add the guardrail that would have caught the original problem — a maximum resource count per root, a plan-duration alert, or a required owner field.
Design a platform repository
Status: design-only. No cloud credentials, backends or resources are used. Terraform CLI 1.17.1 is the version the command shapes are checked against, with hashicorp/aws 6.72.0; verify both before executing anything in a real account. Every identifier below is a placeholder.
Prerequisites. Terraform CLI 1.17.1 (terraform version), a text editor, and the root decisions from the sections above. No provider credentials are needed; nothing is planned against a cloud API.
Minimal setup. Create labs/p29/ with this shape and fill in the roots on paper first:
labs/p29/
modules/
network/ # subnets, routes, zones; ~> 4.2
service/ # compute, queues, IAM; ~> 2.9
environments/
dev/ main.tf providers.tf dev.tfvars
stage/ main.tf providers.tf stage.tfvars
prod/ main.tf providers.tf prod.tfvars
backends/
dev.s3.tfbackend stage.s3.tfbackend prod.s3.tfbackend
bootstrap/ # state bucket, policy, break-glass role
OWNERS.md
MIGRATION.md
Each environment root is a thin composition: a partial backend "s3" {}, one guarded provider, and two module calls with pinned versions. The backend files differ in key, account and role. The tfvars files carry only values, never credentials.
The ownership table this lab produces:
| Root | Account | Backend key | Apply role | Approval |
|---|---|---|---|---|
| dev | dev account | dev/terraform.tfstate | dev-apply | none |
| stage | stage account | stage/terraform.tfstate | stage-apply | one reviewer |
| prod | prod account | prod/terraform.tfstate | prod-apply | two reviewers + change window |
- Write the tree. Write the repository tree above with real directory names, then add the bootstrap root and one
OWNERS.mdrow per root: owner, approver, on-call rotation, backend key, cloud account and apply window. - Draw the dependency graph. Network publishes subnet IDs, data publishes an endpoint, the service root consumes both. Mark every edge that crosses a root boundary and write the exact value that crosses it.
- Fill the ownership table for dev, stage and prod. Each row must name an account or subscription, a backend key, an apply role, an approval rule (none, one reviewer, two plus a window) and the person accountable.
- Run the credential test on paper. For each root, list everything a stolen CI token for that root could change. The lab fails if any token reaches more than one environment, or if a workload root can administer the state bucket.
- Rehearse the backend guard. Describe what happens when the stage pipeline is pointed at
prod.s3.tfbackend. The expected answer is a failure fromallowed_account_idsbefore any resource is read, not a successful apply in the wrong account. - Write one migration record. Pick one module out of a hypothetical 900-resource root and write the migration record: target root, import block for each address,
removedblock withdestroy = false, freeze window, backup command, verification commands and rollback. Do not execute it. - Write the promotion rule. The same module version reaches stage before prod, and the prod pull request links the stage plan. Note the one exception path and who can use it.
- Produce both deliverables. The dependency graph as a diagram and the ownership table as a Markdown table. Both are deliverables, not notes.
Expected observation. The three roots resolve to different backend keys, accounts and roles; every cross-root edge carries exactly one published value; the ownership table names one accountable person per root; and the migration record imports before it removes, with the freeze window covering the overlap.
Failure check. The lab fails if two environments share a backend key or an apply role, if an environment is separated only by a CLI workspace name, if the migration record starts with state rm or force-unlock, if any root has no approver, or if a cross-root dependency relies on reading another team's whole state.
Cost and cleanup. Zero: nothing is provisioned and no plan runs against a cloud API. Delete labs/p29/ after capturing the evidence. A later rehearsal against real accounts is a separate change with its own budget, window and teardown.
Evidence to keep. The repository tree, the sanitized dependency graph, the ownership table, and the migration record with its backup, verification and rollback steps. Redact account IDs and backend keys before sharing; never publish state, plan files or credentials.
Next in the Series
In Drift Detection: Reconcile the Cloud, Configuration and State, we'll explore Investigate out-of-band changes and choose whether to restore intent or adopt the new reality.