Module 6 closed with a sentence: «module 7, Terraform Best Practices, moves up a level and stops talking about the language to talk about how it is worked with as a team and over time». This is the first lesson at that level, and it starts by paying off a specific debt.

In 06-01 we ruled out workspaces as an environment separator and justified why EcoMarket uses one directory with several .tfvars files and several backends. But when we got there we wrote a note: «directory organisation in depth, with its variants and its trade-offs, is the subject of 07-01». That conversation, explicitly postponed, is this lesson.

And the starting point is a confusion that costs a great deal of money and that almost nobody names: splitting the state, splitting the directories and splitting the repositories are three independent decisions. People take them as if they were one, usually without realising they are taking them at all. The result is repositories where separating two teams requires duplicating code, or where reorganising a directory forces you to move resources between states.

This lesson untangles the three decisions, goes right down to the detail of a file and of a resource name, compares the four real project-structure strategies with their trees and their trade-offs, and ends with the EcoMarket repository commented piece by piece and with the antipatterns you recognise by observable symptoms, not by aesthetic opinions.

  1. The three decisions everybody confuses

When somebody asks «how do I organise my Terraform?», they are usually mixing up three questions that have different answers, depend on different factors and can be changed separately.

Decision What it really governs How it materialises Cost of changing it later
How the STATE is split Blast radius of the plan, duration of the apply, locking, permissions over the state One state file per root configuration; they are connected with terraform_remote_state High: resources have to be moved between states (state mv, import, removed)
How the DIRECTORIES are split What runs together, which .tfvars applies, which path shows up in the command Folder tree in the repository Medium: if the state does not move, it is a git mv plus adjusting backend paths
How the REPOSITORIES are split Write permissions over the code, owners, review speed, versioning and publishing One or several Git repositories Low–medium: move files and repoint source; the state never notices

Read that again, paying attention to the last column. The expensive decision is the state one, and it is precisely the one taken without thinking, because it happens as a side effect of creating a directory with a backend.tf inside it.

The real relationships between the three

  • A directory with a terraform { backend ... } block is a root configuration and has its own state. Therefore every new root splits the state. That is the only mandatory link between directory and state.
  • A directory that is a module (no backend, invoked with source) splits nothing: its resources go into the state of whoever invokes it. This was said in 04-01 and it is the most frequent misunderstanding in the ecosystem.
  • A repository can contain many roots and many modules. And a module can live in its own repository and be consumed by roots in other repositories, like terraform-aws-ecomarket-network from 04-04.
flowchart TD
    subgraph REPO["Repository: ecomarket-infra"]
        direction TB
        R1["infra/network/<br/><b>root</b> · backend.tf"]
        R2["infra/app/<br/><b>root</b> · backend.tf"]
        M1["modules/network/<br/>module · no backend"]
        M2["modules/data/<br/>module · no backend"]
    end

    R1 --> M1
    R2 --> M2
    R1 --> E1[("State 1<br/>ecomarket/dev/network")]
    R2 --> E2[("State 2<br/>ecomarket/dev/app")]
    E1 -.->|"terraform_remote_state"| R2

    style R1 fill:#e0f2fe,stroke:#0369a1
    style R2 fill:#e0f2fe,stroke:#0369a1
    style M1 fill:#f3e8fd,stroke:#7c3aed
    style M2 fill:#f3e8fd,stroke:#7c3aed

Two roots, two states, two modules that have no state of their own, one repository. The three decisions are all there and they are visibly different.

The question that puts the conversation in order

Before moving a single file, answer these three separately:

  1. Which set of resources do I want to be able to plan, apply and break without touching the rest? → that defines the states.
  2. What do I want to see in the command and in the pipeline path? → that defines the directories.
  3. Who should be able to approve changes to each thing? → that defines the repositories (or, within one, the per-path owner rules you will see in 07-02).

EcoMarket answered: states per component and per environment; directories per component with the environment as a variables file; one repository for the infrastructure and separate repositories for the published modules. Three different answers to three different questions. The rest of the lesson explains why.

  1. The file as the smallest unit: the naming convention

Terraform does not distinguish file names. It loads every .tf in the directory, concatenates them in memory and builds a single graph. You could put the whole configuration in everything.tf and it would work exactly the same.

That means the naming convention is not for Terraform: it is for people and for the diff. And that is why it matters that it is the same everywhere, because its value lies in predictability.

File Contains Mandatory Note
main.tf The main resources and modules De facto In large roots it is replaced by domain files (section 3)
variables.tf All the variable blocks De facto With description, type and validation, always
outputs.tf All the output blocks De facto It is the public interface: what others consume
versions.tf terraform { required_version, required_providers } Strongly recommended Kept apart from the backend on purpose
providers.tf provider blocks, aliases included Recommended Only in roots; never inside a module (02-04)
backend.tf terraform { backend "s3" { ... } } Roots only Kept apart because it is the only thing that changes per environment
locals.tf locals blocks shared by several files Optional The locals used by a single file stay in that file
data.tf Shared data sources Optional The data used by a single resource stays next to it
moved.tf moved and removed blocks Optional A file of its own so you can delete the whole thing when they expire
terraform.tfvars / *.auto.tfvars Values — Never in modules; roots only
README.md What this is, how it gets deployed Yes Section 10

Why versions.tf and backend.tf are kept apart

It is the least obvious separation and the most useful. Both are terraform blocks, and they could sit in the same file. They are separated because they change for different reasons and with different permissions:

# infra/app/versions.tf — changes when a provider is bumped.
# It is the same for every environment. Its change always comes
# accompanied by an updated .terraform.lock.hcl.
terraform {
  required_version = "~> 1.9"

  required_providers {
    aws    = { source = "hashicorp/aws",    version = "~> 5.60" }
    random = { source = "hashicorp/random", version = "~> 3.6" }
    http   = { source = "hashicorp/http",   version = "~> 3.4" }
  }
}
# infra/app/backend.tf — says WHERE the state lives.
# In EcoMarket it is partial on purpose: the values that change
# per environment arrive with -backend-config. See section 6.1.
terraform {
  backend "s3" {
    bucket       = "ecomarket-tfstate-123456789012"
    region       = "eu-west-1"
    encrypt      = true
    use_lockfile = true
    # key is passed with -backend-config: it is NOT here.
  }
}

A change in versions.tf is a dependency update reviewed by the platform team. A change in backend.tf is a change of where the state lives, and that deserves a more serious review. Separating them makes the diff say by itself what kind of change it is.

The moved.tf you can delete

A small detail with a big return. moved blocks are temporary scaffolding: they exist so that a refactor destroys nothing, and at some point they have to go (03-05, 04-05).

# infra/app/moved.tf
# Expires: 2026-01-15 (three months after v3.2.0). Delete the whole
# file once every environment has applied at least once.

# v3.2.0 — the images bucket moved from the app module to the data module.
moved {
  from = module.app.aws_s3_bucket.images
  to   = module.data.aws_s3_bucket.images
}

# v3.2.0 — the replicas moved from count to for_each by zone.
moved {
  from = module.app.aws_instance.web[0]
  to   = module.app.aws_instance.web["eu-west-1a"]
}

If they were scattered across main.tf and the domain files, nobody would ever delete them and in three years there would be fifty blocks whose reason nobody remembers. With a file of their own and an expiry date written at the top, the cleanup is git rm infra/app/moved.tf and a zero plan.

  1. When to split by resource and when to split by domain

The convention above holds up well to around 300–400 lines of main.tf. Beyond that, a single file stops helping: the diff says nothing, two people collide in the same place and finding a resource means searching by name.

At that point there are two ways to split, and only one of them ages well.

Strategy Example When it works Problem
By resource type s3.tf, iam.tf, ec2.tf, rds.tf Almost never A functional change («add the cache») touches five files. It groups by technology, which is the thing that changes together least
By functional domain network.tf, datastore.tf, app.tf, observability.tf Almost always It requires agreeing on the boundaries, which is real work
By single resource load_balancer.tf with the LB, its listeners, its rules and its certificate When one resource drags along 8–10 satellite resources It multiplies if you overdo it

The rule is the same one that governed module boundaries in 04-01: group what changes together. A load balancer, its listeners, its rules and its security group change in the same PR; its log bucket does not.

infra/app/                          # large root, split by domain
├── versions.tf
├── backend.tf
├── providers.tf
├── variables.tf
├── locals.tf                       # prefix, tags, local.current
├── data.tf                         # caller_identity, AMIs, network remote_state
├── compute.tf                      # launch template + autoscaling
├── load_balancer.tf                # ALB + listeners + rules + certificate
├── datastore.tf                    # data module + connection parameters
├── observability.tf                # alarms, dashboards, log groups
├── guards.tf                       # account check + health check
├── moved.tf
├── outputs.tf
└── README.md

Look at guards.tf. Putting the preconditions and the check blocks from 06-05 in a file of their own has one concrete review advantage: any PR that touches it is modifying a control, and that shows up in the list of changed files without opening the diff. We will come back to this idea in 07-02 when we talk about per-path owners.

Warning. If your main.tf has 900 lines, splitting it into six files improves readability but does not reduce the blast radius or the duration of the apply: it is still the same state and the same graph. Splitting files is cosmetics; splitting states is architecture. Do not mistake the relief of the former for having solved the latter.

  1. Internal ordering of a file and diff readability

Inside a file, the ordering is also pure convention, but it has two measurable effects: how long it takes somebody to find something, and how many lines of noise a change generates.

The recommended ordering inside a resource file:

  1. locals local to this file (if there are any).
  2. data used only by this file.
  3. The resources, in dependency order: first what creates, then what leans on it.
  4. Association resources and rules, next to the resource that owns them.

Inside a resource block, the ordering that produces the most readable diffs:

resource "aws_db_instance" "main" {
  # 1. Identity: what gives it a name and makes it unique.
  identifier = "${local.prefix}-db-${random_pet.suffix.id}"

  # 2. Mandatory arguments, from most to least important.
  engine         = "postgres"
  engine_version = "16.3"
  instance_class = local.current.db_class

  # 3. Optional arguments grouped by topic.
  allocated_storage     = local.current.storage_gb
  max_allocated_storage = local.current.storage_gb * 4
  storage_encrypted     = true

  multi_az                = local.current.multi_az
  backup_retention_period = local.current.retention_days
  deletion_protection     = local.current.protect_deletion

  # 4. References to other resources, together.
  db_subnet_group_name   = aws_db_subnet_group.main.name
  vpc_security_group_ids = [aws_security_group.db.id]

  # 5. Metadata.
  tags = local.common_tags

  # 6. Meta-arguments AT THE END, always: lifecycle, depends_on,
  #    provider, count/for_each (this last one is the exception: it goes on top).
  lifecycle {
    prevent_destroy = true

    precondition {
      condition     = var.environment != "prod" || local.current.retention_days >= 7
      error_message = "Production requires at least 7 days of backup retention."
    }
  }
}

Two nuances that practice teaches:

  • count and for_each are the exception and go right at the top, just after the opening brace. They determine how many instances of the resource there are: whoever reads the block needs to know that before anything else.
  • lifecycle at the end because it tends to be the last thing added and the least read, and because grouping it avoids the pattern of having prevent_destroy hidden in the middle of twenty arguments.

Why this affects the diff

terraform fmt aligns the = signs of a group of contiguous lines. That is good for reading and has a side effect: adding an argument with a long name reindents the whole group.

-  engine         = "postgres"
-  engine_version = "16.3"
-  instance_class = local.current.db_class
+  engine                      = "postgres"
+  engine_version              = "16.3"
+  instance_class              = local.current.db_class
+  manage_master_user_password = true

Four lines of diff for a one-line change. If the block had been divided into groups separated by blank lines — as in the previous example — the new argument would have landed in its own topical group and would have reindented three lines instead of twenty. Blank lines inside a resource are an instrument of diff readability, not decoration.

And the most important rule of all: terraform fmt is not debated, it is run. In a pre-commit hook, in the editor on save and in the pipeline as a mandatory check with terraform fmt -check -recursive. A repository where formatting is a matter of opinion ends up with diffs where 80 % of the lines are whitespace.

  1. Naming: the name in the code versus the name in the cloud

Here lives a confusion that produces ugly code that is hard to refactor. There are two distinct namespaces and they are governed by opposite rules.

Aspect Name in the code (resource "aws_vpc" "HERE") Name in the cloud (name, identifier, bucket)
Who sees it The team, in the editor and the state Everybody: console, invoices, logs, alerts
Must be unique within Its module The account, the region or the world (depending on the resource)
Format snake_case, lower case Whatever the provider imposes; on AWS, kebab-case
Carries the resource type No: aws_vpc.vpc is redundant Sometimes yes: -vpc, -db, it is useful in the console
Carries the environment No: the state says that Yes: local.prefix includes it
Changing it Moves the address → needs moved Replaces the resource → destroys and creates

That last row is the reason this is not cosmetics. Changing the name in the code and changing the name in the cloud have completely different consequences: the first is a safe refactor with five lines of moved; the second destroys the database.

EcoMarket's rules, with examples

Rule Bad Good Why
Do not repeat the type in the name aws_vpc.ecomarket_vpc aws_vpc.main The address already says aws_vpc; the result is aws_vpc.ecomarket_vpc
Do not put the environment in the code aws_db_instance.db_prod aws_db_instance.main The same code serves all three environments
this when the module creates only one of its kind aws_s3_bucket.ecomarket_images_bucket aws_s3_bucket.this (in modules/images) Inside a module called images, the context is already there
A descriptive name when there are several aws_subnet.subnet1, subnet2 aws_subnet.public, aws_subnet.private The number says nothing; the role does
Singular even with for_each aws_subnet.privates aws_subnet.private It is referenced as aws_subnet.private["eu-west-1a"]: the plural jars
snake_case, never hyphens aws_security_group.sg-web aws_security_group.web Hyphens force quotes in some expressions
The name in the cloud comes from local.prefix bucket = "images-ecomarket" bucket = "${local.prefix}-images-${random_pet.suffix.id}" Without the prefix, dev and prod collide in global names

this versus main: the criterion

There are two schools and both are defensible. The one EcoMarket uses is this:

  • Inside a leaf module, the central resource is called this. In modules/network, the VPC is aws_vpc.this. The module is already called network: repeating it inside is noise, and the full address the consumer will see is module.network.aws_vpc.this, which reads perfectly.
  • Inside a root configuration, where there is no module name to give context, a descriptive name is used: main, web, internal. this in a root with forty resources says nothing.
# modules/data/main.tf — the module's central resource is called this.
resource "aws_db_instance" "this" {
  identifier = "${var.base_name}-db-${var.suffix}"
  # ...
}

# Satellite resources of the same module: named by their role.
resource "aws_db_subnet_group" "this" { /* ... */ }
resource "aws_db_parameter_group" "postgres16" { /* ... */ }
resource "aws_security_group" "db" { /* ... */ }
# infra/app/datastore.tf — in a root, descriptive names.
module "data" {
  source  = "ecomarket/ecomarket-data/aws"
  version = "~> 3.0"
  # ...
}

resource "aws_cloudwatch_metric_alarm" "db_cpu_high" { /* ... */ }
resource "aws_cloudwatch_metric_alarm" "db_connections_exhausted" { /* ... */ }

The prefix, once and in one place only

All of EcoMarket's cloud naming comes from a locals block you have been seeing since module 2 and which it is now worth fixing as a repository standard:

# infra/app/locals.tf
locals {
  # The prefix: project + environment. It is what stops dev and prod
  # colliding and what lets the invoice be broken down per environment.
  prefix = "${var.project}-${var.environment}"      # ecomarket-prod

  # The configuration of the active environment, taken from the map.
  current = var.environments[var.environment]

  # Mandatory tags on everything. They are applied via the provider's
  # default_tags, and the modules do not have to do anything.
  common_tags = merge(
    {
      Project     = var.project
      Environment = var.environment
      ManagedBy   = "terraform"
      Owner       = var.contact          # [email protected]
      Repo        = "ecomarket-infra"
    },
    local.current.extra_tags,
  )
}

Two new tags compared with what we had been using, and both are operational rather than decorative: Owner says who to wake up at three in the morning, and Repo says where the code that created that resource lives. When somebody finds an orphan resource in the console, those two tags are the difference between deleting it and opening a two-day investigation. Mandatory tagging stops being a recommendation and becomes a verifiable control in 07-04.

  1. The four project-structure strategies

This is the part 06-01 postponed. There are four real ways to structure a Terraform project with several environments. None is correct in the abstract; each one buys something and pays something.

6.1 Strategy 1 — A single directory with several .tfvars files and several backends

This is EcoMarket's. A single code tree, and the environment comes in through two doors: the variables file and the backend configuration.

flowchart TD
    D["infra/app/<br/><b>one single codebase</b>"]
    D --> V1["dev.tfvars"]
    D --> V2["staging.tfvars"]
    D --> V3["prod.tfvars"]
    D --> B1["backends/dev.hcl"]
    D --> B2["backends/staging.hcl"]
    D --> B3["backends/prod.hcl"]
    B1 --> E1[("ecomarket/dev/app")]
    B2 --> E2[("ecomarket/staging/app")]
    B3 --> E3[("ecomarket/prod/app")]

    style D fill:#e0f2fe,stroke:#0369a1

How it works exactly. The backend block accepts neither variables nor interpolation — you saw this in 03-03 — because it is resolved before anything is evaluated. The way out is the partial configuration: it is left incomplete in the code and completed at init time.

# infra/app/backend.tf — partial on purpose.
terraform {
  backend "s3" {
    region       = "eu-west-1"
    encrypt      = true
    use_lockfile = true
    # bucket and key are NOT here: they arrive with -backend-config.
  }
}
# backends/prod.hcl
bucket = "ecomarket-tfstate-123456789014"
key    = "ecomarket/prod/app/terraform.tfstate"
# The full cycle for production. Each environment names its backend
# AND its variables file: two explicit signals, not one.
cd infra/app

terraform init -reconfigure -backend-config=../../backends/prod.hcl
terraform plan  -var-file=../../environments/prod.tfvars -out=prod.tfplan
terraform apply prod.tfplan

What makes it safe, which is the question that matters and the one 06-01 left half-answered. Four things, and none of them is optional:

  1. -reconfigure on the init. Without it, Terraform tries to migrate the state from the previous backend to the new one and asks you whether you want to copy it. Answering «yes» out of habit when switching from dev to prod copies the development state over the production one. With -reconfigure, Terraform discards the previous configuration without offering migration. It is the flag that makes this model viable.
  2. The .tfvars file is not automatic. They are called prod.tfvars, not prod.auto.tfvars, precisely so that you have to name them. Only common.auto.tfvars loads by itself, and it contains only what is identical across the three environments.
  3. The account guard from 06-05. If somebody initialises with the prod backend and plans with dev.tfvars, the combination is inconsistent: var.environment says dev and the credentials point to account ...14. The guard catches it before the apply. Without that guard, this strategy is not safe, and that is the honest sentence 06-01 was missing.
  4. The pipeline fixes the two things together. Day to day nobody runs those commands by hand in production: the pipeline job receives a single parameter, the environment, and derives the -backend-config and the -var-file from it. A human who makes a mistake touches dev; the road to production goes through a pipeline where environment and backend cannot be mismatched. The detail belongs to module 8.

What it buys: zero code duplication, a single place to fix a bug, a diff between environments that is literally a diff of two .tfvars files.

What it pays: the differences between environments have to fit into variables. The day prod needs a structural resource the others do not have, a count = var.environment == "prod" ? 1 : 0 appears and the slide begins that 06-01 described in its section 5.4. On top of that, init is a stateful step on the machine: a .terraform/ initialised with the wrong backend is a silent trap until you run -reconfigure.

6.2 Strategy 2 — One directory per environment

Each environment has its own directory, with its code, its fixed backend and its provider lock.

flowchart TD
    subgraph T["environments/"]
        DV["dev/<br/>main.tf · backend.tf<br/>terraform.tfvars"]
        ST["staging/<br/>main.tf · backend.tf<br/>terraform.tfvars"]
        PR["prod/<br/>main.tf · backend.tf<br/>terraform.tfvars"]
    end
    M["modules/<br/>network · data · app"]
    DV --> M
    ST --> M
    PR --> M
    DV --> E1[("dev state")]
    ST --> E2[("staging state")]
    PR --> E3[("prod state")]

    style PR fill:#fee2e2,stroke:#b91c1c
    style M fill:#f3e8fd,stroke:#7c3aed

The key, and the reason this strategy works when it is done properly, is the shared arrow towards modules/. Each environment's main.tf must be thin: module invocations and little else. If each main.tf has 340 lines, this is the triple-copy antipattern we denounced in 04-01, not a strategy.

# environments/prod/main.tf — a thin root: 40 lines, not 340.
module "platform" {
  source  = "ecomarket/ecomarket-platform/aws"
  version = "~> 3.2"

  base_name = "ecomarket-prod"
  profile   = "high-availability"
  domain    = "ecomarket.example.com"
  contact   = "[email protected]"
}

# And what ONLY production has lives here, with no conditionals:
resource "aws_wafv2_web_acl" "protection" { /* ... */ }

Look at the second block. That is exactly what strategy 1 cannot do without a conditional, and it is its main advantage: divergence is natural instead of being an exception.

What it buys: trivial per-path permissions, an independent provider lock (you can bump the provider in dev and live with it for two weeks before touching prod, which was objection 5.6 in 06-01), divergence without conditionals, the path visible in the command.

What it pays: the scaffolding is repeated N times. Each environment has its backend.tf, its versions.tf, its providers.tf, its variables.tf. With three environments that is bearable; with twelve, it drifts out of sync. That is exactly the symptom that opens 07-05.

6.3 Strategy 3 — Separation into layers with chained states

The components are split into independent states by rate of change and blast radius, and they communicate with terraform_remote_state. It is orthogonal to the previous two: you can combine it with either.

flowchart LR
    C1["01-network/<br/>VPC, subnets, SG"] --> S1[("network state")]
    C2["02-data/<br/>RDS, S3, secrets"] --> S2[("data state")]
    C3["03-app/<br/>ALB, ASG, DNS"] --> S3[("app state")]

    S1 -.->|"vpc_id<br/>private_subnets"| C2
    S1 -.->|"vpc_id<br/>web_sg_id"| C3
    S2 -.->|"db_endpoint<br/>secret_arn"| C3

    style C1 fill:#dcfce7,stroke:#15803d
    style C2 fill:#fef9c3,stroke:#a16207
    style C3 fill:#e0f2fe,stroke:#0369a1

The numeric prefix on the directories (01-network, 02-data, 03-app) is not decorative: it is the order of application, and it makes it obvious to a newcomer and to the script that walks them. It is the cheapest convention there is for documenting a dependency that Terraform itself cannot see, because each layer is a separate terraform apply.

# 03-app/data.tf
data "terraform_remote_state" "network" {
  backend = "s3"
  config = {
    bucket = "ecomarket-tfstate-${var.account}"
    key    = "ecomarket/${var.environment}/network/terraform.tfstate"
    region = "eu-west-1"
  }
}

locals {
  vpc_id  = data.terraform_remote_state.network.outputs.vpc_id
  subnets = data.terraform_remote_state.network.outputs.private_subnets
}

What it buys: a thirty-second plan instead of a four-minute one; independent locks (the application team deploys while platform touches the network); different IAM permissions per layer; a contained blast radius — a mistake in app cannot destroy the VPC because the VPC is not in its state.

What it pays: the outputs become a public API between configurations, with everything that implies and that you already saw in 04-05; there is an order of application Terraform does not know about and somebody has to remember; and terraform_remote_state grants read access to the complete state, not just to the outputs, with the security warning from 03-03.

Security warning. Before connecting states across different teams with terraform_remote_state, check with the security team what the source state contains. If the data state holds a password, giving app read access is giving that password to everyone who can plan app. The alternative without that risk is to publish the values in Parameter Store or Secret Manager and read them with a provider data source, which can be authorised value by value.

6.4 Strategy 4 — Published modules + very thin roots

The real code lives in versioned, published modules in their own repositories. The infrastructure repository contains only roots of ten or twenty lines that invoke a composition module at a pinned version.

flowchart TD
    subgraph MODS["Module repositories (versioned)"]
        MR["terraform-aws-ecomarket-network<br/>v3.4.1"]
        MD["terraform-aws-ecomarket-data<br/>v3.1.0"]
        MA["terraform-aws-ecomarket-app<br/>v3.6.2"]
        MP["terraform-aws-ecomarket-platform<br/>v3.2.0"]
    end
    MP --> MR
    MP --> MD
    MP --> MA

    subgraph LIVE["ecomarket-live (thin roots)"]
        L1["prod/main.tf<br/>20 lines"]
        L2["staging/main.tf<br/>20 lines"]
    end
    L1 -->|"version = 3.2.0"| MP
    L2 -->|"version = 3.1.0"| MP

    style MP fill:#f3e8fd,stroke:#7c3aed
    style L1 fill:#fee2e2,stroke:#b91c1c

Look at the two final arrows: prod is on v3.2.0 and staging on v3.1.0. That is promotion by version, and it is the property that defines this strategy: an environment is not updated by copying files but by changing a number. The full mechanics, with the promotion process and why it beats copying, is the subject of 07-02.

What it buys: trivial, auditable promotion; the infrastructure code has tests and a CHANGELOG like any other library; product teams consume the platform without being able to touch it; and a security flaw is fixed once and propagates by version.

What it pays: a lot of ceremony. Changing a tag requires a PR in the module, a review, a version tag, a publish and a second PR in the root. In a team of three people that is pure bureaucracy. On top of that, development is more awkward: you have to work with source pointing at a branch or a local path and remember to revert it before merging.

Comparison of the four

Criterion 1. Single directory 2. Directory per environment 3. Chained layers 4. Modules + thin roots
Code duplication None Medium (scaffolding) Medium (per layer) Minimal
Divergence between environments Hard: conditionals Natural Orthogonal By module version
Provider lock per environment No: a single one Yes Yes, per layer Yes
Permissions per environment By pipeline and account Trivial: by path By layer and environment By repository
Blast radius of the plan The whole component The whole component Contained Contained if the module is
Duration of the apply High High Low per layer Depends
Risk of applying in the wrong place Medium: depends on the init Low: the path is visible Low Very low
Ceremony for a small change Minimal Low Low High: two PRs and a version
Promotion between environments Copy values Copy code (risky) Per layer Change a number
Scales well up to ~3–4 environments ~6 environments Many Many
Typical team 1–5 people 3–10 people 5–20, several teams Platform + consumers

And the observation that avoids a sterile argument: these strategies combine. EcoMarket uses 1 for the environment, 3 for the components and 4 for the modules. Choosing «one» is a false dilemma.

  1. Decision criteria: which strategy to choose and when to change

The six factors that really decide, with the threshold at which each one pushes towards another strategy.

Factor Concrete question Threshold that changes the decision
Team size How many people open infrastructure PRs each month? More than 5 → per-path permissions are needed (2 or 4)
Rate of change How often does each component change? If one changes daily and another twice a year → split the state (3)
Blast radius What is the worst thing a mistaken apply can destroy? If a mistake in the application can touch the database → split the state (3)
Permissions per environment Can the same group apply in dev and in prod? If not → directories (2) or repositories (4), not .tfvars
Duration of the apply How long does an apply with no changes take? More than 3–4 minutes → people avoid planning → split the state (3)
Number of environments How many environment × region combinations are there? More than 6–8 → the scaffolding drifts out of sync → 07-05

The decision tree

flowchart TD
    A{"More than one environment<br/>with real production?"} -->|No| S0["One directory, one backend.<br/>Do not overcomplicate."]
    A -->|Yes| B{"Do the environments differ<br/>only in size?"}
    B -->|Yes| C["Strategy 1:<br/>one directory + .tfvars<br/>+ partial backends"]
    B -->|No, they differ in structure| D["Strategy 2:<br/>directory per environment"]
    C --> E{"Does the apply take more than<br/>3 min or is the blast<br/>radius frightening?"}
    D --> E
    E -->|Yes| F["Add strategy 3:<br/>layers with independent<br/>states"]
    E -->|No| G["Stay where you are"]
    F --> H{"Do several teams<br/>consume the same<br/>platform?"}
    G --> H
    H -->|Yes| I["Add strategy 4:<br/>published modules<br/>+ thin roots"]
    H -->|No| J{"More than 8 environment ×<br/>region combinations?"}
    I --> J
    J -->|Yes| K["Terragrunt: 07-05"]
    J -->|No| L["You are fine as you are"]

    style C fill:#e0f2fe,stroke:#0369a1
    style K fill:#fef9c3,stroke:#a16207

And the advice from this lesson that saves the most money: do not adopt a structure for the size you expect to be, adopt it for the size you are. A team of three people that sets up strategy 4 from day one spends six months publishing module versions with a single consumer. Migrating from 1 to 3 when the moment comes costs one well-planned day of work; starting with excess ceremony costs six months of daily friction.

  1. The EcoMarket repository, file by file

This is the real tree of the ecomarket-infra repository as it stands at the end of module 6, with everything built so far.

ecomarket-infra/
├── README.md                       # what it is, how to deploy, who to alert
├── CODEOWNERS                      # per-path owners (07-02)
├── .gitignore                      # what never goes in (07-02)
├── .terraform-version              # 1.9.8 — read by tfenv
├── .tflint.hcl                     # linter rules (07-03)
├── .pre-commit-config.yaml         # fmt, validate, tflint, gitleaks
│
├── backends/                       # partial backend configuration
│   ├── dev.hcl                     #   bucket + key for each environment
│   ├── staging.hcl
│   └── prod.hcl
│
├── environments/                   # values, one file per environment
│   ├── common.auto.tfvars          #   what is the same in all three: project, region
│   ├── dev.tfvars                  #   explicit -var-file, never automatic
│   ├── staging.tfvars
│   └── prod.tfvars
│
├── infra/                          # the root configurations (states)
│   ├── network/                    #   state: ecomarket/<e>/network
│   │   ├── main.tf  variables.tf  outputs.tf
│   │   ├── versions.tf  backend.tf  providers.tf
│   │   ├── guards.tf               #   account check
│   │   └── README.md
│   ├── data/                       #   state: ecomarket/<e>/data
│   │   └── ... (same shape)
│   └── app/                        #   state: ecomarket/<e>/app
│       ├── main.tf  locals.tf  data.tf
│       ├── load_balancer.tf  compute.tf  observability.tf
│       ├── guards.tf               #   account + health check
│       ├── moved.tf                #   with an expiry date
│       ├── variables.tf  outputs.tf  versions.tf  backend.tf
│       └── README.md
│
├── modules/                        # modules NOT yet published (being run in)
│   └── observability/
│       ├── main.tf  variables.tf  outputs.tf  versions.tf
│       ├── README.md  CHANGELOG.md
│       ├── examples/complete/      #   the basis for the tests (07-03)
│       └── tests/*.tftest.hcl
│
├── bootstrap/                      # the backend's chicken-and-egg problem
│   ├── main.tf                     #   creates the state bucket and the role
│   └── README.md                   #   LOCAL state, applied once
│
├── ci/                             # what the machine runs (module 8)
│   ├── plan.sh                     #   init + plan with the right environment
│   ├── apply.sh
│   └── policies/                   #   Conftest rules (07-04)
│       ├── tags.rego
│       └── public_network.rego
│
├── scripts/
│   ├── ephemeral-sweeper.sh        #   destroys expired environments (06-01)
│   └── estimated-cost.sh
│
└── docs/
    ├── architecture.md             # diagram and decisions
    ├── deployment.md               # the procedure, step by step
    ├── incidents.md                # what to do when something goes wrong
    └── adr/                        # architecture decisions, dated
        ├── 0001-backend-s3.md
        ├── 0002-not-using-workspaces.md
        └── 0003-separate-network-and-app.md

The five details that are not obvious and deserve an explanation:

bootstrap/ has local state on purpose. It creates the state bucket and the lock table, so it cannot store its state in a bucket that does not exist yet. It is applied once, when the account is created, and its terraform.tfstate is archived outside the repository (never inside: that is 07-02). It is the only place in the repository where local state is correct.

backends/ and environments/ are sibling, parallel directories. Each environment has exactly one file in each. Keeping them separate allows a different owner rule: changing environments/prod.tfvars is changing the sizing of production; changing backends/prod.hcl is changing where the production state lives, which is far more serious.

modules/ contains only modules that are being run in. network, data, app and ecomarket-platform have already left for their own repositories and are consumed with ~> 3.0 (04-04). observability is still inside because it changes every week and does not yet have a stable interface. The repository is the modules' nursery, and leaving it is an explicit step, not an accident.

ci/plan.sh exists so that the human and the machine run the same thing. If the pipeline does something different from what a person does on their laptop, the failures only show up in the pipeline. A shared script eliminates a whole class of surprises:

#!/usr/bin/env bash
# ci/plan.sh — the ONLY way to plan, locally and in CI.
set -euo pipefail

ENVIRONMENT="${1:?Usage: ci/plan.sh <dev|staging|prod> <component>}"
COMPONENT="${2:?Usage: ci/plan.sh <dev|staging|prod> <component>}"
ROOT="$(git rev-parse --show-toplevel)"

# -reconfigure is MANDATORY: it stops Terraform offering to migrate
# the state from the previous backend to the new one when switching environment.
terraform -chdir="${ROOT}/infra/${COMPONENT}" init \
  -reconfigure \
  -backend-config="${ROOT}/backends/${ENVIRONMENT}.hcl"

# The .tfvars file is named explicitly. common.auto.tfvars loads by itself,
# but the directory has to be given with -var-file for both.
terraform -chdir="${ROOT}/infra/${COMPONENT}" plan \
  -var-file="${ROOT}/environments/common.auto.tfvars" \
  -var-file="${ROOT}/environments/${ENVIRONMENT}.tfvars" \
  -out="${ENVIRONMENT}-${COMPONENT}.tfplan"

echo "Plan saved. Do NOT commit it to the repository: it contains values in the clear."

That final echo is not decoration. A .tfplan file contains the resolved values, sensitive ones included, and it is one of the files that must never go into Git. We will look at it in detail in the next lesson.

docs/adr/ stores decisions, not documentation. An ADR (architecture decision record) is a short, dated file that says what was decided, what alternatives were considered and why they were dropped. 0002-not-using-workspaces.md is literally section 5 of 06-01 summarised in a page. Its value shows up eighteen months later, when somebody new proposes using workspaces and the answer is not «because I say so» but a document with its reasoning and its date — and with the honest possibility that circumstances have changed and the decision should be revisited.

  1. locals and data as layers of indirection

The two mechanisms that most improve the organisation of a repository are also the two that most damage it when they are overused. The difference is concrete and can be phrased as a question.

When a local helps

Case Example Why it helps
A named value local.prefix Gives a name to a concept that appears 40 times
An expensive or long calculation local.subnets = { for i, z in var.zones : z => cidrsubnet(...) } It is written and reviewed once
A centralised decision local.current = var.environments[var.environment] A single point where the environment is resolved
Tag composition local.common_tags = merge(...) The tagging policy in one place

When a local hides

Antipattern Example Observable symptom
An alias with no value local.vpc = module.network.vpc_id To find out where a value comes from you have to jump to another file, and gain nothing
A chain of indirections local.a = local.b, local.b = local.c terraform console is the only way to know what something is worth
Business logic in an expression A four-level nested ternary Nobody dares touch it; one more case is added instead of rewriting it
A giant, global locals A 200-line locals.tf used by everything Changing one line affects resources you did not know were using it

The operational rule: a local must be explainable in a sentence that contains a noun. «The name prefix», «the configuration of the active environment», «the mandatory tags». If the explanation is «the value I pass to this module», it is not a local, it is an alias.

# BAD: three hops to understand one line.
locals {
  network_id = data.terraform_remote_state.network.outputs.vpc_id
  vpc        = local.network_id
  net_id     = local.vpc
}
resource "aws_security_group" "web" {
  vpc_id = local.net_id   # where does this come from? three files later...
}

# GOOD: a single hop, with a name that means something.
locals {
  # The VPC is created by the 01-network layer; here it is only consumed.
  vpc_id = data.terraform_remote_state.network.outputs.vpc_id
}
resource "aws_security_group" "web" {
  vpc_id = local.vpc_id
}

The case of data: discovering versus injecting

In 04-05 the rule «inject, do not discover» appeared, and here it has its organisational version. A data source is an indirection towards the outside world, and it has two properties an argument does not: it does not create an edge in the graph, and it can return something different on every run.

Situation data or argument? Reason
The vpc_id created by another layer of the same repository terraform_remote_state → module variable The module must not know how the network is discovered
The most recent Amazon Linux AMI data "aws_ami" with filters It is genuinely external and changes on its own
The active account and region data "aws_caller_identity" It is the execution context, not a design input
A bucket another team created two years ago data "aws_s3_bucket" It is outside your management; you cannot inject it
A DNS zone managed by the network team data "aws_route53_zone" by name Organisational boundary: you neither create nor control it

And the specific danger of a data source with a broad filter, which is the one that produces incidents:

# DANGEROUS: "the most recent AMI" changes without anyone touching the code.
# A clean plan on Monday can replace every instance on Tuesday.
data "aws_ami" "web" {
  most_recent = true
  owners      = ["amazon"]
  filter {
    name   = "name"
    values = ["al2023-ami-*-x86_64"]
  }
}

# BETTER: the AMI is a versioned decision, not a discovery.
# It is updated in a PR, with its plan reviewed and its deployment window.
variable "web_ami" {
  description = "AMI for the web tier. Promoted dev -> staging -> prod."
  type        = string

  validation {
    condition     = can(regex("^ami-[0-9a-f]{17}$", var.web_ami))
    error_message = "It must be a full AMI identifier, not an alias."
  }
}

The difference between the two versions is the difference between infrastructure that is reproducible and infrastructure that depends on which day it runs. It is the same reasoning that underpins the provider lock file, and it will come back in 07-03 when we discuss why a plan must be deterministic in order to be testable.

  1. The README.md and the minimum viable documentation

The documentation of an infrastructure repository has a very specific reader: somebody who did not write it, with an open incident, at a bad hour. Anything that does not serve that person is optional.

The four questions the README.md must answer on the first screen:

Question What it must contain Typical mistake
What is this? Two sentences and an architecture diagram Starting with «prerequisites»
How do I deploy? The exact, copyable commands, per environment Linking to a wiki that no longer exists
How do I request a change? Branch, PR, who reviews, what to attach Not saying: people apply from their laptops
Who do I alert? Channel, email, who is on call The name of a person who left two years ago
# ecomarket-infra

EcoMarket's infrastructure on AWS (`eu-west-1`), managed with Terraform.
Three environments (`dev`, `staging`, `prod`) in three separate accounts.

![Architecture](docs/architecture.svg)

## Deploying

    ./ci/plan.sh dev app         # generates dev-app.tfplan and shows it
    ./ci/apply.sh dev app        # applies EXACTLY that plan

`staging` and `prod` **are not applied from a laptop**: the pipeline is the
only holder of the `ecomarket-terraform-prod` role. See `docs/deployment.md`.

## Requesting a change

1. Branch from `main`, named `infra/<subject>`.
2. `terraform fmt -recursive` and `./ci/plan.sh dev <component>`.
3. PR using the template: reason, plan summary, replaced resources,
   window and rollback plan.
4. Reviewed by the platform team. `infra/prod`, `backends/` and `ci/policies/`
   also require a security review (see CODEOWNERS).

## Alerts

- Channel `#ecomarket-platform` · [email protected]
- On call: see the rota in `docs/incidents.md`
- **Production has `prevent_destroy` on the database.** If a plan
  proposes destroying it, the plan is wrong: stop and ask.

## Structure

| Directory | What it is |
| --- | --- |
| `infra/` | Root configurations. Each subdirectory is one state |
| `modules/` | Internal modules being run in. The stable ones are published |
| `backends/` | Partial backend configuration per environment |
| `environments/` | Values per environment (`-var-file`) |
| `ci/` | What the pipeline runs. Run it yourself too |
| `docs/adr/` | Why things are the way they are |

What makes that README useful is not its length, it is the last point under «Alerts». It says what an incorrect plan looks like. That is the information a person with an incident cannot deduce and that whoever wrote the code takes for granted.

Generated versus written documentation

For modules, terraform-docs automatically generates the table of inputs and outputs from the description fields. That solves the mechanical part and guarantees it does not go stale, because the pipeline fails if the README does not match the code.

# In the pre-commit hook and also as a check in CI.
terraform-docs markdown table --output-file README.md \
  --output-mode inject modules/observability

But terraform-docs cannot generate what really matters: why the module exists, what decisions it encapsulates, what it does NOT do, and what you need to know before bumping a major version. That is written by hand and goes above the generated table. The rule: generated for the what, written for the why.

  1. Antipatterns with observable symptoms

These are the four that come up again and again. What matters is not the label but the symptom, because that is what lets you detect them before they do damage.

The .tfvars nobody knows whether it has been applied

Symptom: somebody asks in the channel «is this in prod.tfvars applied or pending?» and nobody knows for sure. Somebody runs a plan to find out.

Cause: the variables file is under version control but the apply is manual and leaves no trace. The repository says what should be there; the state says what is there; and nobody has compared the two for weeks.

Real effect: a sizing change from a month ago is still unapplied, and the day somebody applies an urgent change they will drag that one along too, with a plan much bigger than expected and at the worst possible moment.

What fixes it:

  1. The apply is run by the pipeline on merge to main, not by a person (module 8).
  2. A scheduled plan that runs every night across the three environments and warns if it does not come out at zero:
# scripts/drift.sh — run every night by the pipeline.
# Exit code 2 from -detailed-exitcode means "there are pending changes".
set -uo pipefail
for ENVIRONMENT in dev staging prod; do
  for COMPONENT in network data app; do
    ./ci/plan.sh "$ENVIRONMENT" "$COMPONENT" >/dev/null 2>&1
    terraform -chdir="infra/${COMPONENT}" plan -detailed-exitcode \
      -var-file="environments/${ENVIRONMENT}.tfvars" >/dev/null
    case $? in
      0) echo "OK     ${ENVIRONMENT}/${COMPONENT}: no changes" ;;
      2) echo "DRIFT  ${ENVIRONMENT}/${COMPONENT}: there are pending changes" ;;
      *) echo "ERROR  ${ENVIRONMENT}/${COMPONENT}: the plan failed" ;;
    esac
  done
done

Drift between the code and reality is an operational problem, not an organisational one, but it manifests itself as an organisational problem. It has its own treatment in 09-03.

The common catch-all module

Symptom: there is a module called common, shared, base or utils. Its variables.tf has 40 variables, half of them optional with a default value. Each consumer uses a different subset and none uses more than half.

Cause: it was created in order to «avoid repeating code» without a boundary of responsibility. Every time somebody needed something, they added it there.

Real effect: three measurable consequences. One, it cannot be versioned: any change affects every consumer, so everything is MAJOR or nothing is. Two, the blast radius is total: touching one line for team A forces a review of team B's plan. Three, nobody deletes it, because nobody knows who uses what.

What fixes it: the one-sentence test from 04-01: if you cannot describe what the module does in a sentence without using the word «and», it is not a module. It is split by responsibility, with moved inside each new piece so the state never notices, and each part is published with its own versioning.

The 2,000-resource state

Symptom: the most objective of them all, because it is measured with a clock. terraform plan with no changes takes more than three minutes. People have started using -target «to go faster». Somebody has seriously proposed setting -refresh=false by default.

Cause: everything is in a single root configuration. It usually comes from a mass import or from years of growth without splits.

Real effect: the plan takes so long that people plan less; with fewer plans, drift grows; -target leaves the state in partial situations; and an apply that fails halfway has a blast radius of 2,000 resources. On top of that, the lock is a single one: while somebody is applying, nobody else can touch anything.

What fixes it: splitting into layers (strategy 3), moving resources with terraform state mv between states or, better, with the removed + import block pair you saw in 03-05 and 06-04, verifying a zero plan after each batch. It is a well-planned day's work, not something you improvise on a Friday.

Practical threshold. Above around 300–400 resources in a single state, the plan starts to hurt; above 1,000, separation stops being optional. It is not a rule of the product, it is experience of where a team's workflow breaks.

The main.tf.old copy

Symptom: the repository contains files called main.tf.old, main.tf.bak, network-old.tf.disabled, or an old/ directory.

Cause: somebody wanted to keep the previous version «just in case». It is Git acting as a manual backup.

Real effect: it depends on the extension, and that is where the trap lies.

File name Does Terraform load it? Consequence
main.tf.old No (it does not end in .tf) Noise, confusion and forgotten secrets in a file nobody reviews
main.tf.bak No Same
network_old.tf YES Duplicate resources, repeated addresses or an apply that creates unexpected things
old/main.tf Not from the parent But yes if somebody runs terraform inside that directory

The third row is the dangerous one and it really does happen: somebody renames main.tf to main_v1.tf thinking that disables it, and Terraform loads it all the same because it still ends in .tf. The result is a duplicate-names error if you are lucky, or an apply that creates duplicate resources if the renaming was more creative.

What fixes it: delete it. It is in Git. git log -p -- infra/app/main.tf recovers any previous version, and git revert undoes a whole change. If something must be kept «just in case», it is kept with a Git tag, not with a file. And if a file must live in the repository but never be loaded, the correct extension is .tf.example or .tf.tpl, not .tf with a suffix in the name.

Common Errors and Tips

Believing that splitting files reduces the blast radius. It is the most expensive misunderstanding in this lesson. Ten 90-line files and one 900-line file produce exactly the same graph, the same state, the same plan time and the same lock. To reduce the blast radius you have to split the state, and that means separate root configurations.

Putting a provider block inside a module. It is still the most frequent error in the ecosystem, and now that we are talking about organisation it is worth repeating: a module with a provider inside cannot be used with for_each, cannot be cleanly removed from the state and ties its consumers to a configuration they did not choose. Providers are declared in the root and passed with providers = { aws = aws.secondary } (02-04).

Naming resources with the environment inside. aws_db_instance.db_prod works right up to the day you want to use the same code in staging. The environment goes in local.prefix, which affects the name in the cloud; the address in the code is the same in all three environments, and that is why the same state mv works in all of them.

Forgetting -reconfigure when switching environment. With strategy 1, this is what separates a safe workflow from an accident. Without -reconfigure, Terraform offers to copy the state from the previous backend to the new one, and a «yes» out of habit overwrites production. Tip: do not leave it to anybody's discipline, put it in ci/plan.sh and forbid running bare terraform init.

A global locals.tf that everybody touches. Once the locals file goes past 100 lines, it has stopped being a help and has become a coupling. Tip: the locals used by a single file live in that file; locals.tf holds only what is genuinely cross-cutting — prefix, tags, active environment — and rarely more than thirty lines.

Confusing an ADR with documentation. An ADR is not updated: it is written once, dated, and if the decision changes another one is written that supersedes it (0007-revisit-0002.md). Its value lies precisely in being a historical record. Rewriting them destroys the only thing they contribute.

Leaving .terraform/ initialised with the wrong backend. With strategy 1, your local directory remembers the last init. Practical tip: a shell prompt that shows the active environment, or simply always running through ci/plan.sh, which reinitialises. Losing ten seconds on every init is cheaper than an apply in the wrong account.

Adopting the structure from the blog of a company with a thousand engineers. The structures that get published come from organisations with dedicated platform teams and dozens of teams. Copying them into a team of four imports all of their ceremony and none of their problems. Tip: start with the simplest one that solves today's problem and write down in an ADR what the symptom is that will make you change.

Exercises

Exercise 1: untangling the three decisions

A company has this repository and two specific complaints:

company-infra/
├── dev/
│   ├── main.tf        (620 lines)
│   ├── backend.tf
│   └── terraform.tfvars
├── staging/
│   ├── main.tf        (618 lines, almost identical)
│   ├── backend.tf
│   └── terraform.tfvars
└── prod/
    ├── main.tf        (655 lines, diverged)
    ├── backend.tf
    └── terraform.tfvars

Complaints: (a) the prod plan takes four and a half minutes, and the application team has started using -target; (b) the data team needs to be able to change the database without the network people approving the PR, but today any change touches main.tf.

You are asked to:

  1. Classify each complaint according to which of the three decisions in section 1 produces it.
  2. Propose a target structure, with its tree.
  3. State which decisions change and which is the most expensive to carry out, and why.
  4. Write the order of the migration steps and what check validates each one.

Exercise 2: naming and files

Review this fragment from an EcoMarket root and correct everything that violates the conventions in sections 2, 4 and 5. Justify each correction and, for those that change a resource's address in the state, say what has to be added so that nothing is destroyed.

# infra/app/terraform.tf

resource "aws_s3_bucket" "s3_bucket_ecomarket_images_prod" {
  bucket = "images-ecomarket"
  tags   = { Name = "images" }
}

resource "aws_security_group" "sg-web-prod" {
  name   = "sg-web-prod"
  vpc_id = local.network_vpc_id
  lifecycle { create_before_destroy = true }
  description = "web"
}

locals {
  network_vpc_id = local.vpc
  vpc            = data.terraform_remote_state.network.outputs.vpc_id
}

resource "aws_subnet" "private_subnets" {
  for_each   = var.zones
  vpc_id     = local.network_vpc_id
  cidr_block = each.value
}

Exercise 3: choosing a strategy with criteria

For each scenario, choose a strategy (or combination) from section 6, justify it with at least three of the six factors from section 7, and say what the symptom would be that would make you change strategy later on.

  • A. Two people, one product, two environments (dev and prod) that differ only in machine size. 90-second apply.
  • B. Twelve people in three teams (network, data, product), three environments, six-minute apply, and the network team insists on approving any change to the VPC or to security groups.
  • C. A five-person platform team serving eight product teams. Each team wants its own database and its own service, following the same pattern, and none of them should be able to touch the network.
  • D. Same as B, but the company has just opened in three new regions: there are now 3 environments × 4 regions = 12 combinations.

Solutions

Solution 1

1. Classification of the complaints.

Complaint Decision that produces it Why
(a) 4.5-minute plan and use of -target How the STATE is split Everything is in a single root per environment; the state includes network, data and application, and the refresh walks through all of them
(b) Cross-team approvals How the DIRECTORIES are split (and, by extension, the repositories) Everything lives in one main.tf; Git's owner rules work by path, and here there is only one path

Note that neither of them is produced by the repository decision: a single repository is perfectly adequate here, and splitting it would solve a problem that does not exist. That is exactly the confusion section 1 sets out to avoid.

2. Target structure — strategy 3 (layers) combined with strategy 1 (single directory and .tfvars), because environments that have not diverged do not justify tripling the code:

company-infra/
├── backends/
│   ├── dev.hcl  staging.hcl  prod.hcl     # one key per environment and layer
├── environments/
│   ├── common.auto.tfvars
│   ├── dev.tfvars  staging.tfvars  prod.tfvars
├── infra/
│   ├── 01-network/      ← network team    (own state)
│   ├── 02-data/         ← data team       (own state)
│   └── 03-app/          ← product team    (own state)
├── modules/
├── ci/
└── CODEOWNERS

And the CODEOWNERS that resolves complaint (b), with the detail in 07-02:

/infra/01-network/  @company/network-team
/infra/02-data/     @company/data-team
/infra/03-app/      @company/product-team
/backends/          @company/platform @company/security

The backend keys now include the layer, just as in EcoMarket: company/<environment>/<layer>/terraform.tfstate.

3. What changes and what is expensive.

  • The directory decision changes: from three per environment to three per layer. Cheap: a git mv and adjusting paths.
  • The state decision changes: from 3 states (one per environment) to 9 (3 environments × 3 layers). This is the expensive one, because real resources have to be moved between state files. A mistake here means orphan resources (they exist in the cloud, they are in no state) or duplicates (in two states at once, and the first apply tries to recreate them).
  • The repository decision does not change. Correct: there is no complaint that would justify it.

The prod divergence (655 lines against 618) has to be analysed before anything is moved: you need to know whether those are differences that fit in .tfvars or whether they are structural. If there were resources that exist only in production, either they get parameterised with count, or prod needs strategy 2 for that particular layer.

4. Order of the migration and the check for each step.

Step Action Check that validates it
0 terraform state pull > backup-<environment>-<date>.tfstate in all three The three files exist and jq '.resources | length' gives the expected count
1 Analyse the prod divergence with a diff of the three main.tf files A written list of differences, classified as «fits in .tfvars» or «structural»
2 Create the new tree with no backend, with the code split by layer terraform validate passes in all three layers
3 Migrate one layer and one environment: start with 01-network in dev terraform plan in the new layer comes out at zero
4 Repeat layer by layer in dev, in the order 01 → 02 → 03 Zero plan in each; terraform_remote_state resolves
5 Repeat everything in staging, with dev working for at least 48 h Zero plan
6 Repeat in prod, in a maintenance window and with the team available Zero plan and a platform health check
7 Delete the old directories and their states (after 30 days) Nobody has needed the backups

The mechanism for each move is the removed + import pair from 03-05 and 06-04: you declare removed in the source state (which lets go of it without destroying it) and an import block in the target. The alternative with terraform state mv -state-out= also works, but it leaves no trace in the code and is harder to review in a PR.

The non-negotiable criterion is the zero plan. If after moving a layer the plan proposes creating or destroying something, the move is incomplete and you have to stop there, not «carry on and look at it later».

Solution 2

# infra/app/storage.tf   ← 1. The file was called terraform.tf

# 2. Resource name: no type, no environment, no project.
#    The environment is supplied by local.prefix; the type, by the address.
resource "aws_s3_bucket" "images" {
  # 3. The name in the cloud DOES carry a prefix and a random suffix:
  #    the S3 namespace is global and "images-ecomarket"
  #    would collide between environments (and probably already exists).
  bucket = "${local.prefix}-images-${random_pet.suffix.id}"

  # 4. No tags of its own: the provider's default_tags already applies
  #    local.common_tags. If something specific were needed,
  #    it would be added, and Name adds nothing that bucket does not say.
}

resource "aws_security_group" "web" {     # 5. snake_case, no hyphens, no environment
  # 6. name_prefix + create_before_destroy: with a fixed `name`, the replacement
  #    fails because the name is still taken by the old group.
  name_prefix = "${local.prefix}-web-"

  # 7. A useful description: the AWS one is immutable, changing it replaces.
  description = "Inbound HTTP/HTTPS traffic to the EcoMarket web tier"

  vpc_id = local.vpc_id

  tags = local.common_tags

  # 8. Meta-arguments at the end, in expanded form.
  lifecycle {
    create_before_destroy = true
  }
}

# 9. A single indirection, with a name that means something.
locals {
  # The VPC is created by the 01-network layer; here it is only consumed.
  vpc_id = data.terraform_remote_state.network.outputs.vpc_id
}

# 10. Singular: it is referenced as aws_subnet.private["eu-west-1a"].
resource "aws_subnet" "private" {
  for_each = var.zones

  vpc_id            = local.vpc_id
  cidr_block        = each.value
  availability_zone = each.key       # 11. missing: without this, AWS chooses
  tags              = local.common_tags
}

The mandatory moved blocks. Three of the corrections change the resource's address in the state. Without these blocks, Terraform sees the old resources as «no longer in the code» (destroys them) and the new ones as «not in the state» (creates them). For a bucket holding production images, that is data loss:

# infra/app/moved.tf
# Expires: 2026-04-20. Delete once the three environments have applied.

moved {
  from = aws_s3_bucket.s3_bucket_ecomarket_images_prod
  to   = aws_s3_bucket.images
}

moved {
  from = aws_security_group.sg-web-prod
  to   = aws_security_group.web
}

# One entry per key: for_each does not accept a moved of the whole resource
# when the keys change. Here the keys are the same, so moving the whole
# resource is enough.
moved {
  from = aws_subnet.private_subnets
  to   = aws_subnet.private
}

What moved does NOT save, and has to be said in the PR. Changing bucket from "images-ecomarket" to "${local.prefix}-images-..." is a replacement: the name of an S3 bucket is immutable, and changing it destroys the bucket and creates another, empty one. That change is not made with a moved, it is made with a planned data migration:

  1. Create the new bucket with the correct name, without touching the old one.
  2. Copy the contents (aws s3 sync) and verify counts and checksums.
  3. Change the application so it reads from the new one.
  4. Import the old bucket if it has to be kept, or retire it with removed and delete it by hand after a grace period.

The same goes for the security group's name. It is exactly the kind of change a reviewer must catch in the plan by spotting a forces replacement, and that is the subject of 07-02.

Solution 3

Scenario A — two people, two environments, differences in size.

Strategy 1 (single directory + .tfvars + partial backends), and nothing more.

  • Team size: two people do not need per-path permissions; they can talk to each other.
  • Duration of the apply: 90 seconds bothers nobody; splitting the state would add terraform_remote_state and an order of application without gaining anything.
  • Number of environments: two. The duplication strategy 1 avoids is small, but so is its cost.
  • Divergence: size only, which is exactly what a var.environments of type map(object(...)) solves.

Symptom for changing: the first count = var.environment == "prod" ? 1 : 0 that appears (a sign that the divergence has stopped being about size → strategy 2), or the apply going past three minutes (→ strategy 3).

Scenario B — twelve people, three teams, six-minute apply, network approval.

Strategy 3 (layers with chained states) on top of strategy 1 for the environments.

  • Rate of change: the network changes quarterly and the application every week. It is the canonical criterion from 04-05 for separating configurations.
  • Duration of the apply: six minutes to change one tag is what makes people stop planning. Split into layers, each one drops below two.
  • Permissions: the network team's demand is met with per-path CODEOWNERS, which requires the network to have its own directory. With a single main.tf it is impossible.
  • Blast radius: with separate states, a mistake in the application layer cannot destroy the VPC, because the VPC is not in its state. That is a real control, not a convention.

Symptom for changing: more teams starting to consume the same layers and beginning to request changes to them (→ add strategy 4), or the number of environments × regions growing (→ 07-05).

Scenario C — a platform for eight product teams.

Strategy 4 (published modules + thin roots), on a strategy 3 base.

  • Team size: nine teams in total is exactly where the ceremony of publishing versions stops being bureaucracy and becomes protection. A badly made change would affect eight teams at once.
  • Permissions: «none of them should be able to touch the network» is a repository requirement, not a directory one. The network lives in the platform repository; the teams consume a module and receive a vpc_id they cannot modify.
  • Blast radius: each team has its root, its state and its lock. One team's apply cannot touch another's, and with eight teams that would happen daily.
  • Rate of change: the common pattern (the product-service module) evolves slowly and with versions; each team's own code, quickly. Separating them by versioning lets product adopt v4 when it can, not when platform publishes.

Symptom for changing: teams starting to copy the module instead of consuming it, a sign that the interface does not cover their cases and has to be reviewed with them; or the composition module accumulating thirty variables, a sign of the «catch-all» from section 11.

Scenario D — 12 environment × region combinations.

Keep 3 + 1, and evaluate Terragrunt.

  • Number of environments: 12 is the threshold. With strategy 2 there would be 12 nearly identical backend.tf files, and the measurable symptom is that they will already have drifted out of sync at least once.
  • Duplication: twelve copies of providers.tf, of versions.tf and of the terraform_remote_state blocks is pure scaffolding, exactly what Terragrunt generates by convention.
  • Blast radius and permissions: they do not change relative to B, and that is the key point: Terragrunt does not replace the layered architecture, it wraps it.

Honesty before adopting: if the four regions are identical and differ only in region and CIDR, perhaps twelve roots are not needed but four CLI workspaces inside each environment, which is case B of section 8 of 06-01. Terragrunt is adopted when the duplication is real and measured, not when it is anticipated. The full analysis, with the table of what it solves and what it does not, is 07-05.

Conclusion

Organising Terraform code is not a matter of taste: each structural decision buys a concrete operational property and pays a concrete price.

  • There are three decisions, not one. How the state is split, how the directories are split and how the repositories are split. The state one is the expensive one to reverse and the one taken without thinking; the repository one is the cheap one and the one most argued about.
  • Splitting files is cosmetics; splitting states is architecture. Ten files and one big file produce the same graph, the same plan and the same lock.
  • The file-naming convention is for people and for the diff. versions.tf and backend.tf are separated because they change for different reasons; moved.tf goes on its own so it can be deleted in one go with its expiry date written down.
  • In large roots you split by domain, not by resource type. network.tf, datastore.tf, load_balancer.tf. Grouping by technology groups what changes together least.
  • There are two namespaces. The one in the code is snake_case, with no type and no environment, and changing it costs five lines of moved; the one in the cloud comes from local.prefix, and changing it destroys the resource.
  • The four strategies can be combined. EcoMarket uses 1 for the environment, 3 for the components and 4 for the modules.
  • Strategy 1 is safe because of four things together: mandatory -reconfigure, non-automatic .tfvars, the account guard from 06-05 and a pipeline that derives backend and variables from the same parameter. Without all four, it is not.
  • The six criteria that decide are team size, rate of change, blast radius, permissions per environment, duration of the apply and number of environments. Each one has an observable threshold.
  • Adopt the structure for your current size, with an ADR that says what the symptom is that will make you change. Migrating when the time comes costs a day; premature ceremony costs months.
  • A local must be explainable with a noun; if the explanation is «the value I pass to this thing», it is an alias and it hides. A data source with a broad filter turns a clean plan into a surprise replacement: what has to be reproducible is versioned, not discovered.
  • The README has a reader: somebody who did not write the code, with an open incident. It must say what this is, how it gets deployed, how to request a change, who to alert and what an incorrect plan looks like.
  • The four antipatterns are recognised by measurable symptoms: the .tfvars nobody knows whether it has been applied (and its remedy, the nightly drift plan), the catch-all module that cannot be versioned, the state whose plan takes more than three minutes, and the main.tf.old copy which, if it is called .tf, Terraform loads all the same.

Everything above takes one thing for granted that we have not yet examined: that this repository is in Git and that the team knows what to put in it. And that assumption is more delicate than it looks, because Git applied to infrastructure is not Git applied to an application. Here there are files that must never go in — a state, a saved plan, a .tfvars with a password — and whose mistake is not fixed with a correcting commit, because what leaks, leaks forever. There are long-lived branches that in software are an inconvenience and in infrastructure are a risk, because the real world changes while your branch sleeps. There is a promotion between environments that half the teams do by copying files when it should be moving a tag. And there is a PR review that does not consist of reading code, but of reading a plan and recognising the three or four signals that mean «this destroys something».

The next lesson, Version Control, deals with all of that: EcoMarket's .gitignore commented line by line, the emergency procedure for when somebody has already pushed a secret, the branching strategy that works in IaC, promotion as a version change, the reviewer's checklist for a Terraform PR and why git revert almost never reverts the infrastructure.

© Copyright 2026. All rights reserved