The previous lesson ended by naming the class of problem no debugging tool fixes: when what is broken is neither the code nor the provider, but the state. An orphaned lock after a cancelled job. An apply that died halfway and left half an environment created. A state file that cannot be read. A resource that exists in the cloud and that Terraform knows nothing about. Two states that each believe they own the same resource.

There is nothing to debug there. You have to recover, and that has procedures.

This lesson differs from the previous two in one important respect: every section is an operational procedure, designed to be run under pressure, often in the small hours, sometimes with the shop down. That is why they all follow the same structure — observable symptom, cause, verification, procedure, what to review afterwards — and that is why they all include the step people skip when they are in a hurry: the backup before you touch anything.

There is an asymmetry worth internalising before we start. A syntax error is corrected and gone. A badly handled state error propagates: a force-unlock on a live apply corrupts the state; a state push of the wrong version erases the knowledge of fifty resources; a state rm on the wrong state turns managed infrastructure into orphans. On this terrain, the wrong action is worse than inaction, and the correct reflex when in doubt is to stop and verify, not to try and see.

General warning for this lesson. Three commands appear repeatedly and all three are destructive without any real confirmation: terraform force-unlock (which removes a protection without checking whether it was needed), terraform state push (which overwrites the entire remote state, without asking) and terraform state rm (which makes Terraform forget a resource, leaving it orphaned in the cloud). None of the three is run without first doing terraform state pull > copy-$(date +%s).json. None.

  1. The six state problems, by frequency and severity

# Problem Frequency Severity Observable symptom Usual cause Section
1 An orphaned lock Very high Low Error acquiring the state lock with a Who from a machine that no longer exists A cancelled CI job, kill -9, a closed laptop §2
2 An interrupted apply High High The job died halfway; half an environment created Runner timeout, manual cancellation, network error §3
3 Orphaned resources High Medium They exist in the cloud, terraform state list does not know them; AlreadyExists on apply An Atlantis PR closed after applying, a cancelled apply, a forgotten state rm §5
4 Persistent drift Medium Low The same change on every plan, even after you apply it An attribute normalised by the API, default_tags, autoscaling §7
5 A corrupt state Low Very high Error refreshing state, invalid JSON, a higher Terraform version Concurrent writes, a full disk, an interrupted push §4
6 Overlapping states Very low Critical Two applys that undo each other A badly verified migration, a duplicated import §8

Notice the inverse relationship between the two middle columns: what happens most is the least serious, and what happens least is what can bring the platform down. That is why the order of this lesson follows frequency and not severity: you will resolve the orphaned lock a hundred times, and overlapping states, with luck, never.

flowchart TD
    A["Something is wrong with the state"] --> B{"Can Terraform<br/>READ the state?"}
    B -->|No| C["A corrupt or<br/>inaccessible state → §4"]
    B -->|"No, there is a lock"| D["An orphaned lock → §2"]
    B -->|Yes| E{"Does the plan propose<br/>something unexpected?"}

    E -->|"It wants to CREATE something<br/>that already exists"| F["Orphaned resources → §5<br/>or an interrupted apply → §3"]
    E -->|"It wants to CREATE something<br/>that was deleted by hand"| G["The reverse problem → §6"]
    E -->|"It proposes the SAME change<br/>over and over"| H["Persistent drift → §7"]
    E -->|"It wants to DESTROY what<br/>another pipeline just created"| I["Overlapping states → §8<br/>STOP EVERYTHING"]
    E -->|No| J["It is not a state<br/>problem"]

    style C fill:#fee2e2,stroke:#b91c1c
    style I fill:#fee2e2,stroke:#b91c1c
    style J fill:#dcfce7,stroke:#15803d

  1. An orphaned lock

03-04 introduced locking and the checklist to run before a force-unlock. Here it is completed with what module 8 added: the ephemeral runner that got cancelled and of which nothing remains to ask.

2.1. The symptom

╷
│ Error: Error acquiring the state lock
│
│ Error message: operation error DynamoDB: PutItem, https response error StatusCode: 400,
│ RequestID: K3J8M2N4P6Q8R0S2, ConditionalCheckFailedException: The conditional request
│ failed
│ Lock Info:
│   ID:        a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47
│   Path:      ecomarket-tfstate/ecomarket/prod/app/terraform.tfstate
│   Operation: OperationTypeApply
│   Who:       runner@fv-az1234-567
│   Version:   1.9.5
│   Created:   2026-09-23 02:14:22.481293 +0000 UTC
│   Info:
│
│ Terraform acquires a state lock to protect the state from being written by multiple
│ users at the same time. Please resolve this issue above and try again.
╵

Every field decides something, and reading them all before acting is the difference between a safe force-unlock and one that corrupts the state:

Field Value What it decides
ID a3f1c9d2-... The exact argument for force-unlock. It is not invented or truncated
Path .../ecomarket/prod/app/terraform.tfstate Confirms which state. If you were expecting staging, the problem is not the lock
Operation OperationTypeApply The serious data point. With Plan, forcing is almost harmless; with Apply there may be a half-finished write
Who runner@fv-az1234-567 An ephemeral GitHub Actions runner. It no longer exists
Version 1.9.5 If it does not match yours, there are two different configurations pointing at the same state
Created 02:14:22 UTC Its age. Against the current time you decide whether it is alive

2.2. The verification checklist

Before forcing anything, you have to answer these questions in writing, in the team channel. The "in writing" is not bureaucracy: it is what forces you to check instead of assume, and what leaves a record if the sequence of events has to be reconstructed later.

# Question How it is checked The answer that blocks the force-unlock
1 How long has it been locked? Created against date -u Less than 20 minutes with Operation: Apply
2 Does Who correspond to a living machine? Is it an ephemeral runner? Is it a person? If it is a person and they have not answered
3 Is there a CI job running against this state? The CI's API (§2.3) Any job in the in_progress state
4 Is there recent cloud activity from that role? CloudTrail (§2.3) Writes in the last 10 minutes
5 Do I have a copy of the current state? terraform state pull > copy.json Not having one

Question 4 is the one module 8 made necessary and the one most people leave out. A runner can be cancelled in the CI's interface while the Terraform process stays alive for a few seconds, finishing off calls. CloudTrail does not lie.

2.3. Verifying that nobody is really applying

#!/usr/bin/env bash
# ci/check-lock.sh — checks whether a lock really is orphaned.
# Usage: ci/check-lock.sh <environment> <component>
set -euo pipefail

ENVIRONMENT="${1:?}"; COMPONENT="${2:?}"
KEY="ecomarket/${ENVIRONMENT}/${COMPONENT}/terraform.tfstate"
ACCOUNT=$(jq -r ".${ENVIRONMENT}" ci/accounts.json)

echo "=== 1. The lock record in DynamoDB ==="
aws dynamodb get-item \
  --table-name ecomarket-tfstate-locks \
  --key "{\"LockID\":{\"S\":\"ecomarket-tfstate/${KEY}\"}}" \
  --query 'Item.Info.S' --output text | jq .

echo "=== 2. Active CI jobs against this state ==="
gh run list --repo ecomarket/ecomarket-infra \
  --status in_progress --limit 20 \
  --json databaseId,name,displayTitle,createdAt,url \
  --jq ".[] | select(.name | test(\"${ENVIRONMENT}\"))"

echo "=== 3. Recent writes by the apply role (CloudTrail) ==="
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=Username,AttributeValue="ecomarket-terraform-${ENVIRONMENT}" \
  --start-time "$(date -u -d '15 minutes ago' +%Y-%m-%dT%H:%M:%SZ)" \
  --max-results 25 \
  --query 'Events[].{time:EventTime,event:EventName}' --output table

echo "=== 4. The current time (to compare against Created) ==="
date -u +%Y-%m-%dT%H:%M:%SZ

The output of point 1 deserves a look because it contains information the error message summarises:

{
  "ID": "a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47",
  "Operation": "OperationTypeApply",
  "Info": "",
  "Who": "runner@fv-az1234-567",
  "Version": "1.9.5",
  "Created": "2026-09-23T02:14:22.481293Z",
  "Path": "ecomarket-tfstate/ecomarket/prod/app/terraform.tfstate"
}

The interpretation of point 3 is the important part:

  • An empty table. No writes from the apply role in fifteen minutes. Combined with a Created from three hours ago, the lock is orphaned with high confidence.
  • Recent events. There is a live apply. Do not force it. Wait, or find out which job it is.
  • Events that stop abruptly N minutes ago. That is the signature of a dead process: it was writing and it stopped. The lock is orphaned, but the apply was left halfway and the real problem is the one in §3.

2.4. The procedure

flowchart TD
    A["Error acquiring the state lock"] --> B["1. Read EVERY field<br/>of the Lock Info"]
    B --> C{"Operation?"}
    C -->|Plan| D["Low risk"]
    C -->|Apply| E["HIGH risk:<br/>there may be a half-finished write"]

    D --> F{"Is Created more<br/>than 20 min ago?"}
    E --> F
    F -->|No| G["WAIT.<br/>It is probably alive"]
    F -->|Yes| H["2. ci/check-lock.sh"]

    H --> I{"Any active<br/>CI jobs?"}
    I -->|Yes| G
    I -->|No| J{"Writes in<br/>CloudTrail &lt; 10 min?"}
    J -->|Yes| G
    J -->|No| K["3. Backup<br/>state pull"]

    K --> L["4. force-unlock with the EXACT ID"]
    L --> M["5. plan -refresh-only<br/>what was left halfway?"]
    M --> N{"Does the plan match<br/>what was expected?"}
    N -->|Yes| O["Resume the deployment"]
    N -->|No| P["An interrupted apply → §3"]

    style G fill:#fef3c7,stroke:#b45309
    style E fill:#fee2e2,stroke:#b91c1c
    style O fill:#dcfce7,stroke:#15803d
# --- Step 3: the backup. It is NOT optional.
terraform state pull > "/tmp/state-prod-app-$(date +%Y%m%d-%H%M%S).json"
jq '{version, serial, lineage, resources: (.resources | length)}' \
  /tmp/state-prod-app-*.json
{
  "version": 4,
  "serial": 1847,
  "lineage": "8f3a2b1c-4d5e-6f70-8192-a3b4c5d6e7f8",
  "resources": 43
}

Write those four numbers down. serial and lineage are the state's identity and you are going to need them if this gets complicated (§4).

# --- Step 4: force it, with the EXACT ID from the message.
terraform force-unlock a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47
Do you really want to force-unlock?
  Terraform will remove the lock on the remote state.
  This will allow local Terraform commands to modify this state, even though it may
  still be in use. Only 'yes' will be accepted to confirm.

  Enter a value: yes

Terraform state has been successfully unlocked!

Warning. force-unlock only deletes the lock marker. It does not cancel the process that created it, it does not revert anything, it does not check whether an apply is in flight. If the lock was real, you have just created by hand exactly the race condition the lock existed to prevent. And -force, to skip the confirmation, only makes sense in a script that has already done all the verifications: in an interactive session, that pause is your last chance to read the ID.

2.5. What to review afterwards

Forcing the unlock is never the end of the procedure. If the Operation was Apply, you have to find out what was left done:

# 1. What does Terraform think is there, against what really is?
#    -refresh-only proposes no configuration changes: only reconciliation.
terraform plan -refresh-only -out=refresh.tfplan

# 2. Read it in JSON, which is clearer than the text.
terraform show -json refresh.tfplan \
  | jq -r '.resource_drift[]?
           | "\(.address): \(.change.actions | join(","))"'

Three possible outcomes:

Outcome Meaning Action
No drift The apply never got as far as writing anything, or it finished writing before it died Resume the deployment normally
Drift on some resources The refresh found differences between the state and the cloud Review them one by one; probably §3
Resources the plan wants to create They were created in the cloud and never reached the state Orphaned resources → §5

And the record, which is what turns an incident into learning:

<!-- docs/incidents/2026-09-23-lock-prod-app.md -->
# Orphaned lock in prod/app

- **Detected:** 2026-09-23 05:40 UTC, on launching the morning deployment.
- **Lock ID:** a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47
- **Who:** runner@fv-az1234-567 (GitHub Actions, run 9182, cancelled by timeout)
- **Operation:** Apply. **Created:** 02:14 UTC (3h 26m old).
- **Verification:** no active jobs; no writes in CloudTrail since 02:31.
- **Prior copy:** /tmp/state-prod-app-20260923-054112.json (serial 1847, 43 resources).
- **Action:** force-unlock at 05:44. Subsequent `plan -refresh-only`: no drift.
- **Root cause:** the apply exceeded the job's 45-min timeout because of the creation
  of `aws_db_instance.replica` (Multi-AZ, ~50 min).
- **Fix:** `timeout-minutes: 90` on the apply job, and `timeouts { create = "90m" }`
  on the resource. PR #412.

The root-cause section is the one that prevents the next incident. An orphaned lock is almost never the problem: it is the symptom of a job getting cancelled, and jobs get cancelled for reasons that can be fixed.

  1. An apply interrupted halfway

The most serious of the frequent problems, and the worst understood.

3.1. What really happens when an apply dies

The key is when Terraform writes the state, and the answer surprises a lot of people: after every resource, not at the end.

sequenceDiagram
    participant T as Terraform
    participant A as AWS API
    participant S as Remote state (S3)

    T->>A: CreateVpc
    A-->>T: vpc-0a1b...
    T->>S: write state (serial 1848)
    Note over S: The VPC is ALREADY in the state

    T->>A: CreateSubnet
    A-->>T: subnet-0c3d...
    T->>S: write state (serial 1849)

    T->>A: CreateDBInstance
    Note over T,A: 40 minutes of waiting...
    rect rgb(254, 226, 226)
        Note over T: SIGKILL: the runner<br/>exceeds its timeout
    end
    Note over A: RDS IS STILL CREATING<br/>the instance
    Note over S: The state has the VPC and the subnet.<br/>It does NOT have the database.
    Note over S: The LOCK is still in place.

From this come the section's four operational truths:

  1. Whatever was created before the cut-off is in the state. Terraform writes incrementally. You do not lose all the progress.
  2. The resource that was in flight is the problem. It may have been created in the cloud without reaching the state. It is candidate number one for an orphaned resource.
  3. The cloud has no idea Terraform died. RDS carries on building the instance. Five minutes later it exists, and nobody manages it.
  4. The lock stays in place, which is §2 of this lesson. That is why the two problems always arrive together.

3.2. The verification procedure

# --- Step 1: a copy, always the first thing.
terraform state pull > "/tmp/state-before-$(date +%s).json"

# --- Step 2: how far did the state get?
#     The serial says how many writes there were. Compare it with the one from
#     the last successful apply (the pipeline records it, see §11).
jq '{serial, resources: (.resources | length)}' /tmp/state-before-*.json
{
  "serial": 1849,
  "resources": 41
}
# --- Step 3: what the apply that died was planning to do.
#     The approved plan is stored as a job artefact (08-01 §6).
gh run download 9182 --repo ecomarket/ecomarket-infra --name plan-prod
terraform show -json plan.tfplan \
  | jq -r '.resource_changes[]
           | select(.change.actions != ["no-op"])
           | "\(.address)\t\(.change.actions | join(","))"' | column -t
aws_vpc.main                   create
aws_subnet.private[0]          create
aws_subnet.private[1]          create
aws_db_instance.main           create
aws_db_instance.replica        create
aws_ecs_service.web            create
# --- Step 4: what is actually in the state now.
terraform state list > /tmp/in-state.txt
cat /tmp/in-state.txt
# --- Step 5: the comparison, which is the diagnosis.
terraform show -json plan.tfplan \
  | jq -r '.resource_changes[]
           | select(.change.actions | contains(["create"]))
           | .address' | sort > /tmp/planned.txt

comm -23 /tmp/planned.txt <(sort /tmp/in-state.txt)
aws_db_instance.replica
aws_ecs_service.web

Translation: six resources were planned for creation; four are in the state; aws_db_instance.replica and aws_ecs_service.web are not. And now comes the question that decides everything:

3.3. Do the missing ones exist in the cloud?

#!/usr/bin/env bash
# ci/exists-in-cloud.sh — for every resource missing from the state,
# check whether it really exists in AWS.
set -euo pipefail

echo "--- aws_db_instance.replica ---"
aws rds describe-db-instances \
  --db-instance-identifier ecomarket-prod-db-replica \
  --query 'DBInstances[0].{status:DBInstanceStatus,created:InstanceCreateTime,arn:DBInstanceArn}' \
  --output json 2>/dev/null || echo "DOES NOT EXIST"

echo "--- aws_ecs_service.web ---"
aws ecs describe-services \
  --cluster ecomarket-prod --services ecomarket-prod-web \
  --query 'services[0].{status:status,created:createdAt,arn:serviceArn}' \
  --output json 2>/dev/null || echo "DOES NOT EXIST"

echo "--- And the general check: what did the role create during the apply's window? ---"
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=Username,AttributeValue=ecomarket-terraform-prod \
  --start-time "2026-09-23T02:14:00Z" --end-time "2026-09-23T03:00:00Z" \
  --query 'Events[?starts_with(EventName, `Create`)].{time:EventTime,event:EventName,resource:Resources[0].ResourceName}' \
  --output table
--- aws_db_instance.replica ---
{
  "status": "available",
  "created": "2026-09-23T02:21:47Z",
  "arn": "arn:aws:rds:eu-west-1:123456789014:db:ecomarket-prod-db-replica"
}
--- aws_ecs_service.web ---
DOES NOT EXIST

The diagnosis is complete, and these are two different situations needing two different actions:

Resource In the state In the cloud Situation Action
aws_db_instance.replica No Yes An orphaned resource Import it (§5)
aws_ecs_service.web No No It was never created Nothing: the next apply creates it

The CloudTrail table at the end is the safety net: if a CreateX shows up for something that was not on your list, it is another orphan you had not considered.

3.4. How to carry on safely

# 1. Unlock (§2), if the lock is still in place.

# 2. Import whatever was orphaned. With Terraform 1.5+, in the code,
#    which is reviewable in a PR (06-04).
# infra/data/imports.tf
# TEMPORARY — recovery from the interrupted apply of run 9182 (2026-09-23).
# The replica was created in AWS at 02:21 and the apply died before saving it.
# Remove this block after applying. Incident: docs/incidents/2026-09-23-*.md
import {
  to = aws_db_instance.replica
  id = "ecomarket-prod-db-replica"
}
# 3. Verify that the import produces a CLEAN plan. This is the
#    step that validates that the real resource matches the code.
terraform plan -out=recovery.tfplan

terraform show -json recovery.tfplan \
  | jq -r '.resource_changes[]
           | select(.change.actions != ["no-op"])
           | "\(.address): \(.change.actions | join(","))"'

What you expect to see: aws_db_instance.replica: no-op after the import, and aws_ecs_service.web: create. If the plan proposes modifying the imported replica, there are differences between the code and what AWS created; review them before applying. If it proposes replacing it, stop: applying would destroy and recreate a production replica.

# 4. Apply, with a longer timeout than the one that killed the previous run.
terraform apply recovery.tfplan

What you never do: relaunch the CI job without having done this verification. The retried apply will find DBInstanceAlreadyExists for the replica and fail again, or — worse — if the name carries a random suffix, it will create a second replica and leave you paying for two production databases with neither of them properly managed.

3.5. Prevention: do not cancel brutally

The root cause is almost always in the pipeline, and it has a fix:

Measure Effect Where
The job's timeout-minutes greater than the timeouts of the slowest resource The runner does not kill a legitimate apply The workflow
timeouts { create = "90m" } on the slow resources The provider waits as long as it takes The HCL
A concurrency group with cancel-in-progress: false for the apply A new push does not cancel an apply in progress 08-01 §11
Documenting that an apply is not cancelled from the interface It is a one-click action with hours-long consequences The CONTRIBUTING.md
# The configuration that prevents 80% of these incidents.
concurrency:
  group: terraform-apply-${{ inputs.environment }}
  # CRITICAL: false. With true, a push to main during a 40-minute apply
  # kills it halfway and produces exactly this incident.
  cancel-in-progress: false

jobs:
  apply:
    timeout-minutes: 120      # greater than the timeouts{} of the slowest resource

  1. A corrupt or truncated state

Infrequent and very serious. It is the only section where you can genuinely lose work.

4.1. The symptoms

╷
│ Error: Error refreshing state: state snapshot was created by Terraform v1.11.2, which is
│ newer than current v1.9.5; upgrade to Terraform v1.11.2 or greater to work with this state
╵

This is not corruption: it is a version warning, and it is one of the good ones. Somebody ran Terraform 1.11.2 against this state — their laptop, another branch of the pipeline — and the format was upgraded. The state is perfectly fine; what is not fine is your version. The fix is to align versions, not to recover anything.

The underlying lesson: this error is the signal that the Terraform version is not pinned somewhere. If CI uses 1.9.5 and somebody runs 1.11 locally, this will happen again. required_version in the code and a pinned version in the workflow prevent it.

╷
│ Error: Error loading state: unexpected end of JSON input
╵

This one is corruption. The JSON is truncated: a write that got cut off halfway, a full disk, an interrupted state push.

╷
│ Error: Failed to load state: invalid character '\x00' looking for beginning of value
╵

Null bytes: the file was written badly or uploaded in binary mode when it should not have been.

╷
│ Error: Invalid legacy provider address
│
│ This configuration or its associated state refers to the unqualified provider "aws".
│ You must complete the Terraform 0.13 upgrade process before upgrading to later versions.
╵

A very old state. This is not corruption, it is a pending migration.

4.2. Verify before panicking

# 1. Is the remote file valid JSON?
aws s3 cp s3://ecomarket-tfstate/ecomarket/prod/app/terraform.tfstate \
  /tmp/current-state.json

jq empty /tmp/current-state.json && echo "VALID JSON" || echo "CORRUPT JSON"

# 2. If it is valid, does it have the structure it should?
jq '{version, terraform_version, serial, lineage,
     resources: (.resources | length)}' /tmp/current-state.json

# 3. Size and last bytes: a truncation is visible at a glance.
ls -l /tmp/current-state.json
tail -c 200 /tmp/current-state.json
-rw-rw-r-- 1 joan joan 48213 sep 23 09:14 /tmp/current-state.json
      "schema_version": 2,
      "attributes": {
        "address": "ecomarket-prod-db-noble-

The file ends mid-string. Truncation confirmed.

4.3. The three recovery routes, in order

flowchart TD
    A["Corruption confirmed"] --> Z["0. COPY the corrupt one<br/>before touching anything"]
    Z --> B{"Is there a local<br/>terraform.tfstate.backup?"}
    B -->|Yes| C["ROUTE 1<br/>Check serial and lineage"]
    B -->|No| D{"Does the bucket have<br/>versioning enabled?"}

    C --> E{"Is the serial<br/>the expected one?"}
    E -->|Yes| F["state push<br/>+ a verification plan"]
    E -->|"No / far too old"| D

    D -->|Yes| G["ROUTE 2<br/>list-object-versions<br/>pick the last good one"]
    D -->|No| H["ROUTE 3<br/>Rebuild by importing"]

    G --> I["Download, check<br/>serial + lineage + resources"]
    I --> J{"Does the lineage match<br/>the one you expected?"}
    J -->|Yes| F
    J -->|No| K["STOP: it is ANOTHER<br/>infrastructure's state"]

    H --> L["terraform state list of the<br/>last backup + a cloud<br/>inventory → import blocks"]

    F --> M["plan: zero changes?"]
    M -->|Yes| N["Recovered"]
    M -->|"It proposes creating<br/>resources that exist"| O["The state is too<br/>old: what was created later is missing<br/>→ complete it with import"]

    style K fill:#fee2e2,stroke:#b91c1c
    style N fill:#dcfce7,stroke:#15803d
    style Z fill:#fef3c7,stroke:#b45309

Step 0, before anything else: keep the corrupt one.

aws s3 cp s3://ecomarket-tfstate/ecomarket/prod/app/terraform.tfstate \
  "/tmp/CORRUPT-$(date +%Y%m%d-%H%M%S).json"

It looks useless and it is not: a corrupt state usually preserves 95% of the information, and if all three routes fail, it will be your source for rebuilding by hand.

Route 1: terraform.tfstate.backup

Terraform keeps a local copy of the state prior to the last operation, in the working directory:

ls -l terraform.tfstate.backup
jq '{serial, lineage, resources: (.resources | length)}' terraform.tfstate.backup
Advantage Limitation
Immediate, with no dependency on anything external It only exists if the last operation was done in this directory
It is exactly the previous state In CI, the directory was destroyed with the runner
— It is one version back, not a history

At EcoMarket, with every apply in CI, this route is almost never available in production. It is useful locally.

Route 2: S3 versioning

The main route, and the reason 03-03 insisted on enabling bucket versioning.

BUCKET=ecomarket-tfstate
KEY=ecomarket/prod/app/terraform.tfstate

# 1. List the versions, newest to oldest.
aws s3api list-object-versions \
  --bucket "$BUCKET" --prefix "$KEY" \
  --query 'Versions[?Key==`'"$KEY"'`].{version:VersionId,date:LastModified,size:Size}' \
  --output table | head -20
-------------------------------------------------------------------------
|                          ListObjectVersions                           |
+------------------------+---------------------------+-----------------+
|          date          |          size             |    version      |
+------------------------+---------------------------+-----------------+
|  2026-09-23T02:31:11Z  |  48213                    |  3HL9mP2nQ8vR4t |
|  2026-09-23T02:21:47Z  |  71455                    |  8vR4tY7wL1zB3c |
|  2026-09-22T19:03:22Z  |  71402                    |  L1zB3cF6xK9mP2 |
|  2026-09-22T11:47:55Z  |  70988                    |  F6xK9mP2nQ8vR4 |
+------------------------+---------------------------+-----------------+

The drop in size is the clue. 71,455 bytes at 02:21, and 48,213 at 02:31. A state does not slim down by 32% in ten minutes unless it has been truncated. The good version is 8vR4tY7wL1zB3c.

# 2. Download the candidate.
aws s3api get-object \
  --bucket "$BUCKET" --key "$KEY" \
  --version-id 8vR4tY7wL1zB3c \
  /tmp/candidate.json

# 3. THE THREE CHECKS. None of them is optional.
jq empty /tmp/candidate.json && echo "✓ Valid JSON"

jq '{version, terraform_version, serial, lineage,
     resources: (.resources | length),
     addresses: [.resources[] | "\(.module // "root").\(.type).\(.name)"] | sort}' \
  /tmp/candidate.json
{
  "version": 4,
  "terraform_version": "1.9.5",
  "serial": 1849,
  "lineage": "8f3a2b1c-4d5e-6f70-8192-a3b4c5d6e7f8",
  "resources": 41,
  "addresses": [
    "root.aws_db_instance.main",
    "root.aws_ecs_cluster.main",
    "root.aws_lb.main",
    "root.aws_subnet.private",
    "root.aws_vpc.main"
  ]
}

What each field verifies, and why all three are mandatory:

Field What it verifies What it means if it does not match
lineage That it is the same line of state, not a different infrastructure STOP. A different lineage means this state describes something else. Pushing it would destroy everything
serial How many writes it has had. It must be the highest one that is valid A lower serial than expected means later operations are missing: there will be orphans
resources and addresses That the resources you expect are there If any are missing, the state is too old

lineage is the check that saves your life. Terraform generates a unique lineage when a state is created and keeps it for ever. Two states with a different lineage are two different infrastructures. The scenario this prevents: recovering by mistake a version of a bucket that holds staging's state under a similar key, pushing it over prod, and having the next plan propose destroying the whole of production because it "does not look like" what the state says. Terraform warns you if the lineages differ, but -force skips the warning, and in the small hours of an incident somebody will reach for it.

# 4. Check the lineage AGAINST the one you had written down.
EXPECTED_LINEAGE="8f3a2b1c-4d5e-6f70-8192-a3b4c5d6e7f8"
CANDIDATE_LINEAGE=$(jq -r .lineage /tmp/candidate.json)

if [[ "$CANDIDATE_LINEAGE" != "$EXPECTED_LINEAGE" ]]; then
  echo "STOP. Different lineage: ${CANDIDATE_LINEAGE} != ${EXPECTED_LINEAGE}"
  exit 1
fi
echo "✓ Lineage correct"

And now the dangerous step:

# 5. Push the recovered version.
terraform state push /tmp/candidate.json

Warning: state push overwrites without asking. There is no interactive confirmation, no diff, no "are you sure?". It overwrites the entire remote state with the file you hand it. The only protections are two automatic checks — that the lineage matches and that the serial is not lower than the remote one — and both are disabled by -force. If you ever find yourself typing terraform state push -force, stop and get a second person: it is the command that has deleted more infrastructure than any other in Terraform's history.

A practical detail: when you recover an earlier version, its serial (1849) may be lower than the corrupt state's (1850), and Terraform will reject it. The correct approach is not -force but raising the candidate's serial:

# Set a serial higher than the remote one, keeping everything else.
REMOTE_SERIAL=$(jq -r .serial /tmp/CORRUPT-*.json 2>/dev/null || echo 0)
jq --argjson s $((REMOTE_SERIAL + 1)) '.serial = $s' /tmp/candidate.json \
  > /tmp/candidate-serial-ok.json

terraform state push /tmp/candidate-serial-ok.json

This keeps both protections (the lineage is still verified) and only relaxes the one that is in the way.

# 6. THE FINAL CHECK, which is what tells you whether you really recovered.
terraform plan -out=verification.tfplan

terraform show -json verification.tfplan \
  | jq -r '.resource_changes[]
           | select(.change.actions != ["no-op"])
           | "\(.address): \(.change.actions | join(","))"'
Outcome Interpretation Action
No changes A perfect recovery Done. Document it
It proposes creating resources you know exist The state predates those creations Import them (§5)
It proposes destroying resources The state contains things that no longer exist §6, and review closely
It proposes modifying many things A possible wrong lineage, or a very old state Stop. Check the lineage again

Route 3: rebuild by importing

When there is neither a backup nor versioning. It is laborious but not impossible, and the full procedure is the one in 06-04.

# 1. An inventory of what exists in the cloud, by tag.
#    This works because local.common_tags puts ManagedBy = terraform
#    on EVERYTHING. This is the moment that convention pays for itself.
aws resourcegroupstaggingapi get-resources \
  --tag-filters "Key=Project,Values=EcoMarket" "Key=Environment,Values=prod" \
  --query 'ResourceTagMappingList[].ResourceARN' --output text | tr '\t' '\n' \
  > /tmp/inventory-prod.txt

wc -l /tmp/inventory-prod.txt
# 2. Generate the import blocks and the configuration from them.
#    -generate-config-out writes the HCL corresponding to each resource.
terraform plan -generate-config-out=generated.tf
# 3. And the quick route when the code does exist (which is the usual case:
#    what was lost is the state, not the repository): write the import
#    blocks by hand from the code and the inventory.

This route is the definitive argument for bucket versioning. Rebuilding EcoMarket's prod state by importing is a day's work for two people with high risk; recovering a version from S3 takes fifteen minutes. Versioning costs pennies a month.

  1. Orphaned resources: they exist in the cloud and not in the state

Module 8's debt: "the Atlantis PR closed after applying, and the apply cancelled halfway".

5.1. The four ways of creating them

Origin How it happens Detectable by
An Atlantis PR closed after applying The "apply before merging" model of 08-05: the apply created the resources, the PR was closed without merging, the code is not on main main's code does not declare them, but they exist and they are in the state
An apply cancelled halfway §3: the resource was created in the cloud and the apply died before saving it They are not in the state
A forgotten state rm Somebody took a resource out of the state "temporarily" to sort something else out and never imported it back They are not in the state
Created by hand Somebody did it in the console during an incident They are not in the state, and sometimes they do not even have tags

The first is different from the other three and is the most dangerous, because it produces the inverse situation: the resources are in the state but not in the code. The next apply from main will destroy them, because from Terraform's point of view they are surplus resources. And nobody expects it, because "we never merged that change".

flowchart TD
    A["Where is the resource?"] --> B{"In the cloud?"}
    B -->|No| C["There is no problem"]
    B -->|Yes| D{"In the state?"}
    D -->|Yes| E{"In main's<br/>code?"}
    D -->|No| F["A classic ORPHAN<br/>Terraform does not know it<br/>→ import or delete"]

    E -->|Yes| G["All correct"]
    E -->|No| H["An INVERSE ORPHAN<br/>(a closed Atlantis PR)<br/>The next apply DESTROYS it"]

    style F fill:#fef3c7,stroke:#b45309
    style H fill:#fee2e2,stroke:#b91c1c
    style G fill:#dcfce7,stroke:#15803d

5.2. Systematic detection

Detection rests on a convention EcoMarket has been applying since 07-01: everything Terraform manages carries ManagedBy = "terraform" in local.common_tags. That tag turns a hard problem into a comparison of two lists.

#!/usr/bin/env bash
# ci/detect-orphans.sh
#
# Compares what exists in AWS with ManagedBy=terraform against what
# EcoMarket's states know about. Anything that is in the cloud and in
# no state is an orphaned resource.
#
# Usage: ci/detect-orphans.sh <dev|staging|prod>
set -euo pipefail

ENVIRONMENT="${1:?Usage: $0 <dev|staging|prod>}"
COMPONENTS=(network data app)
WORK=$(mktemp -d)

echo "=== 1. Cloud inventory (ManagedBy=terraform, Environment=${ENVIRONMENT}) ==="
aws resourcegroupstaggingapi get-resources \
  --tag-filters \
      "Key=ManagedBy,Values=terraform" \
      "Key=Project,Values=EcoMarket" \
      "Key=Environment,Values=${ENVIRONMENT}" \
  --query 'ResourceTagMappingList[].ResourceARN' \
  --output text | tr '\t' '\n' | grep -v '^$' | sort -u > "${WORK}/cloud.txt"

echo "   $(wc -l < "${WORK}/cloud.txt") tagged resources in the cloud"

echo "=== 2. What the states know about ==="
: > "${WORK}/states.txt"
for c in "${COMPONENTS[@]}"; do
  terraform -chdir="infra/${c}" init -reconfigure -input=false \
    -backend-config="../../backends/${ENVIRONMENT}.hcl" >/dev/null

  # ARNs live in different attributes depending on the resource; we collect
  # them all from the state dump.
  terraform -chdir="infra/${c}" state pull \
    | jq -r '.resources[].instances[].attributes
             | (.arn // .id // empty),
               (.task_definition_arn // empty),
               (.execution_arn // empty)' \
    | grep '^arn:' >> "${WORK}/states.txt" || true
done
sort -u "${WORK}/states.txt" -o "${WORK}/states.txt"
echo "   $(wc -l < "${WORK}/states.txt") ARNs known to the states"

echo
echo "=== 3. ORPHANS: in the cloud, in no state ==="
comm -23 "${WORK}/cloud.txt" "${WORK}/states.txt" | tee "${WORK}/orphans.txt"

N=$(wc -l < "${WORK}/orphans.txt")
echo
echo "   Total: ${N} orphaned resources"

echo
echo "=== 4. Who created them and when (the first 5) ==="
head -5 "${WORK}/orphans.txt" | while read -r arn; do
  NAME="${arn##*/}"
  echo "--- ${arn}"
  aws cloudtrail lookup-events \
    --lookup-attributes "AttributeKey=ResourceName,AttributeValue=${NAME}" \
    --max-results 3 \
    --query 'Events[].{time:EventTime,event:EventName,who:Username}' \
    --output text 2>/dev/null || echo "    (no events in the last 90 days)"
done

# Exit code: useful as a pipeline gate.
[[ "$N" -eq 0 ]]

What each block does:

  1. get-resources with three tag filters returns the ARN of everything tagged as Terraform's in that environment. It is the list of "what should be managed".
  2. It walks the three states and extracts every ARN they know about. .arn // .id // empty covers resources that store the ARN in arn and those that store it in id; the following two lines cover particular cases in ECS and API Gateway.
  3. comm -23 returns the lines of the first file that are not in the second: exactly the orphans.
  4. CloudTrail by resource name says who created it and when, which is what decides what to do with it.

An honest limitation: this script finds tagged resources. A resource created by hand during an incident carries no ManagedBy = terraform and will not show up. For that you need the inverse inventory — everything in the account minus what is tagged — which is far noisier and is run quarterly, not weekly.

In the pipeline, as a scheduled detection alongside the drift detection of 08-01 §12:

# .github/workflows/orphans.yml
name: Orphaned resource detection

on:
  schedule:
    - cron: '0 6 * * 1'      # Monday morning
  workflow_dispatch:

jobs:
  detect:
    strategy:
      fail-fast: false
      matrix:
        environment: [dev, staging, prod]
    runs-on: ubuntu-latest
    permissions: { id-token: write, contents: read }
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          # The PLAN role: this only reads. Never the apply one.
          role-to-assume: arn:aws:iam::${{ vars[format('ACCOUNT_{0}', matrix.environment)] }}:role/ecomarket-terraform-plan-${{ matrix.environment }}
          aws-region: eu-west-1

      - id: detect
        run: ci/detect-orphans.sh ${{ matrix.environment }} | tee orphans.txt
        continue-on-error: true

      - if: steps.detect.outcome == 'failure'
        run: |
          gh issue create \
            --repo ecomarket/ecomarket-infra \
            --title "Orphaned resources in ${{ matrix.environment }}" \
            --label "infrastructure,orphans" \
            --body-file orphans.txt
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

5.3. The two ways out: import or delete

flowchart TD
    A["An orphaned resource detected"] --> B{"Who created it<br/>and when?<br/>(CloudTrail)"}
    B --> C{"Is it in use<br/>right now?"}

    C -->|"Yes: it takes traffic,<br/>it holds data,<br/>something depends on it"| D{"Is it in the<br/>code?"}
    C -->|"No: no traffic,<br/>no data,<br/>nothing depends on it"| E{"Does it cost money?"}

    D -->|Yes| F["IMPORT<br/>It is what the code describes"]
    D -->|No| G["Write the code<br/>first, then import"]

    E -->|Yes| H["DELETE<br/>after confirming with the team"]
    E -->|No| I{"Has it been unused<br/>for more than 30 days?"}
    I -->|Yes| H
    I -->|No| J["Tag it as pending<br/>and review in 30 days"]

    style F fill:#dcfce7,stroke:#15803d
    style H fill:#fef3c7,stroke:#b45309

The criterion, in a table:

Situation Decision Reason
It is in the code and in the cloud, missing from the state Import This is exactly the case import exists for
It holds data (a database, a bucket with objects, a volume) Import, even if it is not in the code Deleting destroys data. First import and manage it; then decide
It takes production traffic Import The same: get control of it first
No data, no traffic, created during an incident months ago Delete It is junk that costs money and clutters the inventory
No data, created two days ago, nobody knows what it is Ask before anything else It may be somebody's work in progress
Created by an Atlantis PR that was closed It depends: if the change was good, reopen the PR and merge it; if not, delete The problem is one of process, not of infrastructure

The import procedure, with the check that matters:

# infra/data/imports.tf
# TEMPORARY — recovery of orphans detected on 2026-09-23.
# See docs/incidents/2026-09-23-orphans-prod.md
import {
  to = aws_db_instance.replica
  id = "ecomarket-prod-db-replica"
}

import {
  to = aws_s3_bucket.reports
  id = "ecomarket-prod-reports-quiet-fox"
}
terraform plan -out=import.tfplan

# THE check: after importing, those resources must be no-op.
terraform show -json import.tfplan \
  | jq -r '.resource_changes[]
           | select(.address | test("replica|reports"))
           | "\(.address): \(.change.actions | join(","))"'
aws_db_instance.replica: no-op
aws_s3_bucket.reports: update

update on the bucket means the code and reality differ: probably it is missing the common tags because it was created by hand. Look at what it proposes to change before applying:

terraform show -json import.tfplan \
  | jq '.resource_changes[] | select(.address == "aws_s3_bucket.reports")
        | {before: .change.before.tags, after: .change.after.tags}'

The deletion procedure, with its three protections:

# 1. Confirm that it is not in use. For a bucket:
aws s3 ls s3://ecomarket-prod-reports-quiet-fox --recursive --summarize | tail -3
aws s3api get-bucket-logging --bucket ecomarket-prod-reports-quiet-fox

# 2. Announce it in the team channel with 48 hours' notice,
#    listing exactly what is going to be deleted.

# 3. Tag it rather than deleting, first. If nobody complains within a
#    week, then it gets deleted.
aws s3api put-bucket-tagging \
  --bucket ecomarket-prod-reports-quiet-fox \
  --tagging 'TagSet=[{Key=PendingDeletion,Value=2026-09-30},
                     {Key=Contact,[email protected]}]'

Tagging and waiting rather than deleting is the difference between a professional procedure and a reckless one. An orphaned resource has been there for months; one more week changes nothing, and it avoids the day you discover that that "unused" bucket was the destination of the quarterly reports that are generated every three months.

5.4. The case of the closed Atlantis PR

It deserves a procedure of its own because it is the inverse case and the most surprising.

The symptom: main's plan proposes destroying resources that exist, work, and that nobody remembers creating with a merged PR.

Terraform will perform the following actions:

  # aws_cloudwatch_dashboard.business will be destroyed
  # aws_lambda_function.daily_report will be destroyed
  # aws_cloudwatch_event_rule.daily_report will be destroyed

Plan: 0 to add, 0 to change, 3 to destroy.

The diagnosis:

# 1. Are they in the state? Yes, which is why the plan wants to destroy them.
terraform state list | grep -E "dashboard|daily_report"

# 2. Are they in main's code? No.
git grep -n "daily_report" -- '*.tf'

# 3. Who created them? The PR that applied them.
terraform state show aws_lambda_function.daily_report | grep -E "arn|last_modified"

# 4. Look for the PR closed without merging that touched them.
gh pr list --repo ecomarket/ecomarket-infra --state closed --limit 50 \
  --search "daily_report" \
  --json number,title,closedAt,mergedAt,author
[{
  "number": 397,
  "title": "Daily sales report to Slack",
  "closedAt": "2026-09-18T16:22:04Z",
  "mergedAt": null,
  "author": {"login": "cvidal"}
}]

mergedAt: null with closedAt set: closed without merging, after having applied. It is exactly the flaw 08-05 warned the apply-before-merge model has.

The two ways out, and the decision is not a technical one:

If the change was good If the change should not have gone in
Reopen PR #397, review it and merge it. The code returns to main, the plan is clean again, and the resources carry on existing without anything being touched Apply the destruction deliberately, after confirming with the author. It is the terraform destroy the PR would have done if it had been reverted properly
It is the right answer 90% of the time: somebody closed the PR by mistake or because "it was already applied" The remaining 10%: it was an experiment and the clean-up was forgotten

And the prevention, which is what really solves this, is an automatic check:

# .github/workflows/pr-closed-with-apply.yml
# If a PR is closed WITHOUT merging and Atlantis had applied in it,
# open an issue immediately. Do not leave it until Monday.
name: PR closed after applying

on:
  pull_request:
    types: [closed]

jobs:
  check:
    if: github.event.pull_request.merged == false
    runs-on: ubuntu-latest
    steps:
      - name: Was there an apply in this PR?
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          APPLIED=$(gh pr view ${{ github.event.pull_request.number }} \
            --repo ${{ github.repository }} \
            --json comments \
            --jq '[.comments[] | select(.body | test("apply.*Plan: .*to add|Apply complete"))] | length')

          if [[ "$APPLIED" -gt 0 ]]; then
            gh issue create --repo ${{ github.repository }} \
              --title "PR #${{ github.event.pull_request.number }} closed without merging AFTER APPLYING" \
              --label "urgent,infrastructure" \
              --body "PR #${{ github.event.pull_request.number }} applied infrastructure changes and was closed without merging.

          The resources created are in the state but NOT in \`main\`. The next apply of \`main\` **will destroy them**.

          Action required (see module 9, lesson 3, §5.4):
          1. Check whether the change was meant to go in: reopen and merge the PR.
          2. If it was not: apply the destruction deliberately.

          Do not leave this unresolved: every day that passes raises the chance of a surprise destruction."
          fi

  1. The reverse problem: they are in the state and not in the cloud

Somebody deleted a resource by hand. Terraform finds out at the next refresh.

6.1. The symptom

aws_s3_bucket.reports: Refreshing state... [id=ecomarket-prod-reports-quiet-fox]

Note: Objects have changed outside of Terraform

Terraform detected the following changes made outside of Terraform since the last
"terraform apply" which may have affected this plan:

  # aws_s3_bucket.reports has been deleted
  - resource "aws_s3_bucket" "reports" {
      - id     = "ecomarket-prod-reports-quiet-fox" -> null
      - bucket = "ecomarket-prod-reports-quiet-fox" -> null
    }

Terraform will perform the following actions:

  # aws_s3_bucket.reports will be created
  + resource "aws_s3_bucket" "reports" {
      + bucket = "ecomarket-prod-reports-quiet-fox"
      ...
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Terraform does the right thing: the code says it should exist, it does not exist, it is going to create it. The "Objects have changed outside of Terraform" block is the informational part, and it is the one you have to read: it says what changed from outside.

6.2. The question to ask before applying

Why did they delete it? Recreating without finding out is how an incident gets reopened.

Cause How you find out Correct action
Deleted by mistake CloudTrail: who and when Recreate it, and review manual delete permissions
Deleted deliberately during an incident Ask. The incident record Do not recreate. Take it out of the code with removed (03-05)
Deleted by a lifecycle policy or an external automation Find the automation Decide who is in charge: Terraform or the automation
It expired (a certificate, a temporary credential) The nature of the resource Recreate it, and review the renewal
# Who deleted it and when.
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=ResourceName,AttributeValue=ecomarket-prod-reports-quiet-fox \
  --query 'Events[?contains(EventName, `Delete`)].{time:EventTime,event:EventName,who:Username}' \
  --output table
-------------------------------------------------------------------
|                          LookupEvents                           |
+----------------------+----------------+------------------------+
|        event         |      time      |          who           |
+----------------------+----------------+------------------------+
|  DeleteBucket        | 2026-09-22T18:47:11Z |  cvidal           |
+----------------------+----------------+------------------------+

One person, at 18:47. Before recreating, ask them. They may have deleted the bucket because it contained personal data that had to be erased following a deletion request, in which case recreating it is correct but recreating its contents would not be; or they may have got the wrong account.

6.3. The three outcomes

# A) Recreate: nothing special to do. The plan already proposes it.
terraform apply

# B) Do not recreate: take it out of the code and the state, declaratively.
# infra/data/datastore.tf
# The reports bucket was deleted on 2026-09-22 following a data
# erasure request (INFRA-4830). It is not recreated.
removed {
  from = aws_s3_bucket.reports

  lifecycle {
    # The resource no longer exists in the cloud: it just has to be forgotten.
    destroy = false
  }
}
# C) Recreate, but it is a resource with data: the data has to be restored separately.
#    Terraform creates the container; the contents are another procedure.
terraform apply
aws s3 sync s3://ecomarket-backups/reports/2026-09-22/ \
            s3://ecomarket-prod-reports-quiet-fox/

Case C is the most often forgotten. Terraform manages infrastructure, not data. An apply that recreates a deleted database leaves you with an empty database with the same name, and the plan will say 1 to add with complete equanimity. That is why prevent_destroy is on the resources that hold data, and why restoring from a snapshot is a separate procedure that has to be written down.

  1. Persistent drift that reappears on every plan

03-01 introduced drift. Here we deal with the chronic variant: the plan proposes the same change, you apply it, and at the next plan it is back again.

7.1. The symptom

  # aws_ecs_task_definition.web will be updated in-place
  ~ resource "aws_ecs_task_definition" "web" {
      ~ container_definitions = jsonencode(
          ~ [
              ~ {
                  ~ cpu = 1024 -> 1024
                    ...
                }
            ]
        )
    }

Plan: 0 to add, 1 to change, 0 to destroy.

1024 -> 1024. The same value on both sides. That is the unmistakable signature of a normalisation: the value is equivalent but the textual representation differs.

7.2. The four causes and their diagnosis

Cause How you recognise it Fix
API normalisation The diff shows the same value, or differs only in formatting (JSON key order, capitalisation, whitespace) jsonencode() of an ordered structure, or a scoped ignore_changes
default_tags or another system that tags It is always tags, and they appear and disappear Align default_tags with the resource's tags, or ignore that specific tag
Autoscaling desired_count, min_size, desired_capacity change on their own ignore_changes on that attribute. It is the legitimate case par excellence
Another system managing the same resource A Kubernetes operator, a script, another team Decide who is in charge. It is an organisational problem

Diagnosis with the plan JSON (09-02 §8), which shows the exact values without the text plan's formatting:

terraform plan -out=p.tfplan >/dev/null
terraform show -json p.tfplan \
  | jq -r '.resource_changes[]
           | select(.address == "aws_ecs_task_definition.web")
           | .change
           | {before: .before.container_definitions,
              after: .after.container_definitions}' \
  | jq -r '.before, .after' | while read -r line; do echo "$line" | jq -S .; done

Processing both with jq -S (which sorts the keys) and comparing them is what reveals whether the difference is real or one of ordering:

# The definitive comparison: normalise both and diff them.
terraform show -json p.tfplan \
  | jq -r '.resource_changes[] | select(.address=="aws_ecs_task_definition.web")
           | .change.before.container_definitions' | jq -S . > /tmp/before.json
terraform show -json p.tfplan \
  | jq -r '.resource_changes[] | select(.address=="aws_ecs_task_definition.web")
           | .change.after.container_definitions' | jq -S . > /tmp/after.json

diff /tmp/before.json /tmp/after.json && echo "THEY ARE IDENTICAL: it is normalisation"

7.3. Stabilising it with a properly scoped ignore_changes

resource "aws_ecs_service" "web" {
  name            = "${local.prefix}-web"
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.web.arn
  desired_count   = local.current.initial_replicas

  tags = local.common_tags

  lifecycle {
    ignore_changes = [
      # Autoscaling adjusts desired_count continuously. Terraform sets
      # the INITIAL value; from then on autoscaling is in charge.
      # Without this, every plan proposes going back to the initial replicas,
      # and applying it at peak time cuts the shop's capacity.
      desired_count,

      # Application deployments (the app's pipeline, not this one)
      # update the task definition's revision. Terraform sets
      # the family; the revision is set by whoever deploys.
      task_definition,
    ]
  }
}

The three rules of ignore_changes:

  1. Named attributes, never all. ignore_changes = all disables change detection for the whole resource: somebody could change the security group, the encryption or the execution role and Terraform would say nothing.
  2. A comment explaining who manages that attribute instead. If Terraform ignores it, somebody manages it. If nobody manages it, it should not be ignored.
  3. A dated review. ignore_changes entries accumulate and nobody removes them. EcoMarket's convention: a six-monthly review of every ignore_changes in the repository.
# The inventory that makes that review possible.
grep -rn -A6 "ignore_changes" --include='*.tf' infra/ modules/ \
  | grep -E "ignore_changes|#" \
  | grep -v "^--"

A warning about ignore_changes = all. It shows up in answers on the internet as a quick fix for drift and it is, in practice, switching Terraform off for that resource. The resource stays in the state, keeps appearing in the plan as no-op, and everybody assumes it is managed. It is not: anybody can change anything in it without leaving a trace in any plan. If you genuinely want Terraform not to manage a resource, take it out of the state with removed, which is at least honest.

7.4. The default_tags case

A frequent and very confusing particular case:

provider "aws" {
  region = var.region

  default_tags {
    tags = local.common_tags
  }
}

resource "aws_s3_bucket" "images" {
  bucket = "${local.prefix}-images-${random_pet.suffix.id}"

  # PROBLEM: these tags are ADDED to the default_tags, and some
  # resources produce perpetual drift from the overlap.
  tags = local.common_tags
}

With default_tags active, repeating the same tags in tags produces, on some resource types, a perpetual dance between tags and tags_all. The fix is to pick one of the two mechanisms:

# The option chosen at EcoMarket: default_tags for the cross-cutting ones,
# tags ONLY for what is specific to each resource.
resource "aws_s3_bucket" "images" {
  bucket = "${local.prefix}-images-${random_pet.suffix.id}"

  tags = {
    Content = "catalogue-images"          # specific, not in the common ones
  }
}

  1. Overlapping states: two states, one resource

The worst scenario, and the one 07-05 and 06-04 announced would be dealt with here.

8.1. The symptom

Two pipelines that undo each other's work. On Monday, the data deployment creates a security group; on Tuesday, the app deployment destroys it; on Wednesday, data creates it again.

--- Plan for infra/data, 10:00 ---
  # aws_security_group.db will be created
Plan: 1 to add, 0 to change, 0 to destroy.

--- Plan for infra/app, 14:00, the same day ---
  # aws_security_group.db will be destroyed
Plan: 0 to add, 0 to change, 1 to destroy.

The unmistakable signal: two different states propose opposite actions on the same real resource.

8.2. The chronology of the disaster

Let us reconstruct EcoMarket's case, because understanding how you get there is what teaches you not to get there.

timeline
    title How the overlap happened at EcoMarket
    Day 1 (Tue) : Migration of infra/data to Terragrunt (07-05)
                : terragrunt apply is run in live/staging/data
                : The plan proposes CREATING 23 resources, not 0
                : It is applied "to see if it sorts itself out"
    Day 1 (Tue) : Some resources fail on a name conflict
                : Others are created DUPLICATED with different suffixes
                : The new state has 18 resources; the old one, 23
    Day 2 (Wed) : The old pipeline runs on its schedule
                : It finds its 23 resources, does not see the 18 new ones
                : Everything looks normal
    Day 5 (Sat) : Scheduled drift detection
                : It reports changes in staging that nobody made
                : It is put down to "something from the migration"
    Day 12 (Sat): The new pipeline applies and DESTROYS the old ALB
                : staging is down for 40 minutes
                : It is discovered that there are two states

The three mistakes, in order of importance:

  1. The zero plan was not zero, and it was applied anyway. This is the fundamental mistake. 07-05 said it in as many words: "a plan that proposes creating 23 resources in a migration that was not supposed to create anything is an unmistakable signal that something is wrong, and the only correct path is to stop and diagnose".
  2. The old pipeline was not disabled when the migration started. For twelve days, two systems managed the same infrastructure.
  3. Day 5's drift alert was dismissed without investigation. That was the warning, and it was silenced with a plausible explanation.

8.3. Detection

#!/usr/bin/env bash
# ci/detect-overlap.sh
#
# Looks for ARNs that appear in MORE THAN ONE of EcoMarket's states.
# It should always return nothing. If it returns anything, it is an emergency.
set -euo pipefail

ENVIRONMENT="${1:?Usage: $0 <dev|staging|prod>}"
WORK=$(mktemp -d)

# Every state: the classic components and the migration's.
STATES=(
  "infra/network"
  "infra/data"
  "infra/app"
  "live/${ENVIRONMENT}/network"
  "live/${ENVIRONMENT}/data"
  "live/${ENVIRONMENT}/app"
)

for dir in "${STATES[@]}"; do
  [[ -d "$dir" ]] || continue
  NAME=$(echo "$dir" | tr '/' '_')

  terraform -chdir="$dir" state pull 2>/dev/null \
    | jq -r --arg e "$NAME" \
        '.resources[]?.instances[]?.attributes
         | (.arn // .id // empty)
         | select(startswith("arn:") or startswith("sg-") or startswith("vpc-")
                  or startswith("subnet-") or startswith("i-"))
         | "\(.)\t\($e)"' \
    >> "${WORK}/all.txt" || true
done

echo "=== Identifiers present in more than one state ==="
sort "${WORK}/all.txt" \
  | awk -F'\t' '{ ids[$1] = ids[$1] " " $2; n[$1]++ }
                END { for (i in n) if (n[i] > 1) printf "%s\n    in:%s\n", i, ids[i] }'

echo
echo "(Empty = correct. Any output is an EMERGENCY: see module 9, lesson 3, §8)"

This check should be part of the pipeline from day one of any migration, not discovered afterwards.

8.4. The resolution procedure

flowchart TD
    A["Overlap confirmed"] --> B["1. STOP EVERY pipeline<br/>that touches these states"]
    B --> C["2. A copy of BOTH states<br/>state pull"]
    C --> D["3. Inventory: which real resource<br/>is in which states"]
    D --> E["4. DECIDE which state<br/>owns each resource"]
    E --> F["5. Remove from the NON-owning state<br/>with removed, without destroying"]
    F --> G["6. plan on BOTH:<br/>zero changes in each"]
    G --> H{"Both at<br/>zero?"}
    H -->|No| I["Not resolved.<br/>Back to step 3"]
    H -->|Yes| J["7. Re-enable the pipelines,<br/>one at a time"]
    J --> K["8. Permanent overlap<br/>detection in CI"]

    style B fill:#fee2e2,stroke:#b91c1c
    style I fill:#fef3c7,stroke:#b45309
    style K fill:#dcfce7,stroke:#15803d

Step 1: stop everything. This is not excessive caution: every run of either pipeline can destroy real infrastructure.

# Disable the workflows involved.
gh workflow disable terraform-apply.yml --repo ecomarket/ecomarket-infra
gh workflow disable terragrunt-apply.yml --repo ecomarket/ecomarket-infra

Steps 2 and 3: copy and inventory.

terraform -chdir=infra/data state pull > /tmp/state-old.json
terraform -chdir=live/staging/data state pull > /tmp/state-new.json

# Which resources each one holds, by real ARN.
for f in old new; do
  jq -r '.resources[].instances[].attributes | (.arn // .id // empty)' \
    "/tmp/state-${f}.json" | sort -u > "/tmp/ids-${f}.txt"
done

echo "--- In BOTH (the problem) ---"
comm -12 /tmp/ids-old.txt /tmp/ids-new.txt

echo "--- Only in the old one ---"
comm -23 /tmp/ids-old.txt /tmp/ids-new.txt

echo "--- Only in the new one ---"
comm -13 /tmp/ids-old.txt /tmp/ids-new.txt

Step 4: decide the owner. The decision is architectural, not one of convenience, and it is taken for a whole component, never resource by resource:

Criterion Choose
What is the migration's intended destination? The new one, normally
Which has the complete set of resources? Whichever is complete; the partial one will have to be completed
Which governs the pipeline that is going to be kept? The one being kept
Which has the data-bearing resources correctly recorded? That one, always. The data is in charge

Step 5: remove from the non-owner, without destroying.

# infra/data/removed.tf
# These resources move to being managed from live/staging/data (Terragrunt).
# Migration INFRA-4712, resolution of the overlap of 2026-09-23.
# destroy = false is MANDATORY: the resources still exist and are
# managed by the other state. Without it, they would be destroyed.

removed {
  from = aws_security_group.db
  lifecycle { destroy = false }
}

removed {
  from = aws_db_subnet_group.main
  lifecycle { destroy = false }
}

removed {
  from = aws_db_instance.main
  lifecycle { destroy = false }
}

lifecycle { destroy = false } is the line that separates a resolution from a disaster. A removed block without it destroys the resource. In an overlap, that means deleting infrastructure the other state believes it has. Write it first, before the from, and check it twice.

# Verify BEFORE applying that it destroys nothing.
terraform -chdir=infra/data plan -out=cleanup.tfplan

terraform -chdir=infra/data show -json cleanup.tfplan \
  | jq -r '.resource_changes[]
           | select(.change.actions | contains(["delete"]))
           | "WOULD DESTROY: \(.address)"'

If that query returns anything, do not apply. A correct removed produces a plan that only "forgets": in the output it appears as will no longer be managed by Terraform, never as will be destroyed.

Step 6: the double check.

terraform -chdir=infra/data apply cleanup.tfplan

# And now, BOTH at zero. This is what says it is resolved.
terraform -chdir=infra/data plan -detailed-exitcode \
  && echo "✓ old: no changes"
terragrunt -chdir=live/staging/data plan -detailed-exitcode \
  && echo "✓ new: no changes"

-detailed-exitcode returns 0 only if there are no changes. Both at zero is the success criterion, and there is no other.

Steps 7 and 8: re-enable one at a time, and leave the detection of §8.3 in place as a permanent pipeline check.

8.5. The duplicated import

The other route to an overlap, and it is far easier to cause than the migration:

# In infra/data/imports.tf
import {
  to = aws_s3_bucket.reports
  id = "ecomarket-prod-reports-quiet-fox"
}
# And in infra/app/imports.tf, two weeks later, another person:
import {
  to = aws_s3_bucket.sales_reports
  id = "ecomarket-prod-reports-quiet-fox"    # ← the SAME bucket
}

Terraform gives no error at all. Each state imports the resource and believes it owns it. The first to change a tag will win, and the other will revert it on its next apply.

The prevention is a check before every import, and it belongs in the PR template:

#!/usr/bin/env bash
# ci/verify-import.sh — run BEFORE applying any import block.
# Usage: ci/verify-import.sh <resource-id>
set -euo pipefail

ID="${1:?Usage: $0 <id>}"
FOUND=0

for dir in infra/network infra/data infra/app live/*/*; do
  [[ -d "$dir" ]] || continue
  if terraform -chdir="$dir" state pull 2>/dev/null \
       | grep -qF "$ID"; then
    echo "ALREADY MANAGED in: ${dir}"
    FOUND=1
  fi
done

if [[ "$FOUND" -eq 1 ]]; then
  echo
  echo "DO NOT IMPORT. This resource is already in a state."
  echo "Importing it again produces overlapping states (module 9, lesson 3, §8)."
  exit 1
fi

echo "✓ ${ID} is in no state. The import is safe."

  1. A backend migration that goes wrong

9.1. What can go wrong

Failure Symptom Severity
-migrate-state was chosen when -reconfigure was called for One environment's state ended up written over another's key High
The migration was interrupted halfway The state at the target is incomplete or absent Medium
The target already had a state and it was overwritten The knowledge of another infrastructure was lost Critical
The old backend was deleted before verifying There is no way back Critical

9.2. How to revert it

Reverting is possible as long as the source exists. That is the only reason the correct procedure never deletes the source until days later.

# --- Step 1: what is in each place NOW? ---
aws s3 cp s3://ecomarket-tfstate-old/prod/terraform.tfstate \
  /tmp/source.json 2>/dev/null || echo "The source no longer exists"
aws s3 cp s3://ecomarket-tfstate/ecomarket/prod/app/terraform.tfstate \
  /tmp/target.json

for f in source target; do
  echo "--- ${f} ---"
  jq '{serial, lineage, resources: (.resources | length)}' "/tmp/${f}.json" 2>/dev/null \
    || echo "  (not available)"
done
--- source ---
{ "serial": 1847, "lineage": "8f3a2b1c-4d5e-6f70-8192-a3b4c5d6e7f8", "resources": 43 }
--- target ---
{ "serial": 1, "lineage": "8f3a2b1c-4d5e-6f70-8192-a3b4c5d6e7f8", "resources": 12 }

The diagnosis is immediate: the same lineage (it is the same infrastructure, good) but the target has 12 resources out of 43 and serial: 1. The migration stopped halfway.

# --- Step 2: revert by pointing at the original backend. ---
cat > backend.tf <<'EOF'
terraform {
  backend "s3" {
    bucket         = "ecomarket-tfstate-old"
    key            = "prod/terraform.tfstate"
    region         = "eu-west-1"
    dynamodb_table = "ecomarket-tfstate-locks"
    encrypt        = true
  }
}
EOF

# -reconfigure, NOT -migrate-state: we do not want to copy the target's
# 12 incomplete resources over the source's 43 good ones.
rm -rf .terraform
terraform init -reconfigure

# --- Step 3: verify that we are where we wanted to be. ---
terraform state list | wc -l        # should give 43
terraform plan -detailed-exitcode   # should give 0: no changes

The nuance that decides everything in step 2 is -reconfigure versus -migrate-state, and it is the same one from 09-01 §4.4 applied to the reversion: -migrate-state would copy the incomplete state over the good one, which is exactly the opposite of what you want.

# --- Step 4: clean up the failed target, once step 3 is confirmed. ---
aws s3api delete-object \
  --bucket ecomarket-tfstate \
  --key ecomarket/prod/app/terraform.tfstate

9.3. The correct migration procedure

So that next time no reversion is needed:

#!/usr/bin/env bash
# ci/migrate-backend.sh — a verified backend migration.
set -euo pipefail

echo "=== 1. A copy of the SOURCE state ==="
terraform state pull > "/tmp/pre-migration-$(date +%Y%m%d-%H%M%S).json"
BEFORE=$(terraform state list | wc -l)
SERIAL_BEFORE=$(terraform state pull | jq -r .serial)
LINEAGE=$(terraform state pull | jq -r .lineage)
echo "   ${BEFORE} resources, serial ${SERIAL_BEFORE}, lineage ${LINEAGE}"

echo "=== 2. The target must be EMPTY ==="
if aws s3api head-object --bucket "$TARGET_BUCKET" --key "$TARGET_KEY" 2>/dev/null; then
  echo "ERROR: there is already a state at the target. Migrating would overwrite it."
  exit 1
fi

echo "=== 3. Migrate ==="
terraform init -migrate-state -backend-config="$TARGET_CONFIG"

echo "=== 4. VERIFY: the same number of resources and the same lineage ==="
AFTER=$(terraform state list | wc -l)
LINEAGE_AFTER=$(terraform state pull | jq -r .lineage)

[[ "$BEFORE" == "$AFTER" ]] \
  || { echo "ERROR: ${BEFORE} != ${AFTER} resources"; exit 1; }
[[ "$LINEAGE" == "$LINEAGE_AFTER" ]] \
  || { echo "ERROR: the lineage changed"; exit 1; }

echo "=== 5. VERIFY: the plan must give ZERO changes ==="
terraform plan -detailed-exitcode \
  || { echo "ERROR: the plan proposes changes. STOP AND DIAGNOSE."; exit 1; }

echo "✓ Migration verified. Do NOT delete the source backend for 7 days."

Step 5 is the one missing from the chronology of §8.2. A plan that proposes changes after migrating means the migration was not a migration: it was the creation of a new state. And carrying on "to see if it sorts itself out" is what produced twelve days of two states in parallel.

  1. A secret leaked into the state

07-04 established that the state contains every value in the clear, including the ones marked sensitive. Here is the procedure for when that fact turns into an incident.

10.1. When it is an incident

Situation An incident?
The state is in encrypted S3, with restricted access and versioning No: that is normal operation
The state was pushed to Git by mistake Yes
The state was downloaded to a laptop and shared Yes
Somebody unauthorised has read permission on the bucket Yes
A terraform show -json was published as a public CI artefact Yes (09-02 §8.5)
A debugging output with a secret reached main Yes (09-02 §11.1)

10.2. The procedure: rotate first

flowchart TD
    A["A secret exposed in the state"] --> B["1. ROTATE the secret<br/>NOW. Do not wait."]
    B --> C["2. Verify that the new one<br/>works (the shop is still up)"]
    C --> D["3. Determine the SCOPE:<br/>who could have seen it?"]
    D --> E["4. Clean up the exposure:<br/>Git, artefacts, copies"]
    E --> F["5. Clean the state's<br/>history if appropriate"]
    F --> G["6. Fix the cause:<br/>so it is not there again"]

    style B fill:#fee2e2,stroke:#b91c1c

The order matters and it is counter-intuitive. The instinct is to clean up first — delete the commit, remove the artefact — so that nobody sees it. That is the wrong order: while the secret is valid, the risk exists, and cleaning up takes hours whereas rotating takes minutes. Rotating turns the exposed secret into a useless piece of data, and from then on the clean-up is hygiene, not urgency.

# --- Step 1: rotate. For EcoMarket's database password,
#     which lives in Secrets Manager (07-04).
NEW=$(openssl rand -base64 32 | tr -d '/+=' | head -c 32)

aws secretsmanager put-secret-value \
  --secret-id ecomarket/prod/db/password \
  --secret-string "$NEW"

aws rds modify-db-instance \
  --db-instance-identifier ecomarket-prod-db-noble-bee \
  --master-user-password "$NEW" \
  --apply-immediately

# --- Step 2: verify that the shop is still up.
curl -sf https://ecomarket.example.com/health | jq .
# --- Step 3: scope. Who has read the state?
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=GetObject \
  --start-time "$(date -u -d '30 days ago' +%Y-%m-%dT%H:%M:%SZ)" \
  --query 'Events[?contains(CloudTrailEvent, `ecomarket-tfstate`)].{time:EventTime,who:Username}' \
  --output table

This only works if S3 data-access logging is enabled on the state bucket. If it is not, the conclusion is that you cannot bound the scope, and you have to assume the worst case. Enabling it is one line of configuration and it is worth it.

# --- Step 5: the state's history.
#     Every earlier version in S3 contains the old secret. After rotating,
#     they are useless, but if the organisation's policy requires it:
aws s3api list-object-versions \
  --bucket ecomarket-tfstate \
  --prefix ecomarket/prod/data/terraform.tfstate \
  --query 'Versions[].VersionId' --output text

Warning: deleting state versions destroys your ability to recover. Versioning is what makes route 2 of §4.3 possible. Before deleting versions for secret hygiene, make sure there is a complete copy of the current version somewhere safe, and that the team knows the history is gone. In most cases, rotating is enough and nothing needs deleting: a rotated secret in an old state is not a secret.

Step 6, fixing the cause, which is the only thing that prevents a repeat:

Cause Fix
The state in Git .gitignore with *.tfstate*, and a pre-commit hook that blocks it
A public CI artefact Publish only the summary, never the complete JSON (09-02 §8.5)
A debugging output The debug_ prefix and the CI check
Too many people with access to the bucket Review the bucket's policy: only the Terraform roles
The secret is in the state because Terraform generates it Do not have Terraform generate it. Have the application read it from Secrets Manager at runtime, and have Terraform only create the empty secret

The last row is the fundamental solution and the one 07-04 recommends: if Terraform never sees the value, it is never in the state.

  1. Prevention

Everything above is prevented by six measures, and five of them are configuration.

11.1. Versioning and copies of the state bucket

# infra/bootstrap/state.tf — the state's state.
resource "aws_s3_bucket" "state" {
  bucket = "ecomarket-tfstate"

  lifecycle {
    prevent_destroy = true
  }
}

# THE most important measure in this whole section: without versioning,
# recovery route 2 does not exist.
resource "aws_s3_bucket_versioning" "state" {
  bucket = aws_s3_bucket.state.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "state" {
  bucket = aws_s3_bucket.state.id
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "aws:kms"
      kms_master_key_id = aws_kms_key.state.arn
    }
  }
}

resource "aws_s3_bucket_public_access_block" "state" {
  bucket                  = aws_s3_bucket.state.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

# Keep old versions for 90 days: enough to recover from
# any incident, and without the cost growing indefinitely.
resource "aws_s3_bucket_lifecycle_configuration" "state" {
  bucket = aws_s3_bucket.state.id

  rule {
    id     = "retain-versions-90-days"
    status = "Enabled"
    filter {}

    noncurrent_version_expiration {
      noncurrent_days = 90
    }
  }
}

# A copy in another region: it protects against the loss of a whole region and,
# above all, against an accidental deletion of the bucket.
resource "aws_s3_bucket_replication_configuration" "state" {
  depends_on = [aws_s3_bucket_versioning.state]
  bucket     = aws_s3_bucket.state.id
  role       = aws_iam_role.state_replication.arn

  rule {
    id     = "copy-to-eu-central-1"
    status = "Enabled"
    filter {}

    destination {
      bucket        = aws_s3_bucket.state_copy.arn
      storage_class = "STANDARD_IA"
    }

    delete_marker_replication {
      status = "Disabled"     # a deletion at the source is NOT propagated
    }
  }
}

delete_marker_replication: Disabled is deliberate: if somebody deletes the state in the main region, the copy survives. Propagating the deletion would turn the backup into a mirror of the disaster.

11.2. The other five measures

Measure What it prevents Where it is
Locking with DynamoDB Concurrent writes → a corrupt state 03-04
Separation by component An incident affecting the whole infrastructure; huge states that are slow to refresh 07-01
cancel-in-progress: false on the apply An interrupted apply (§3), which is the cause of orphaned locks and orphaned resources 08-01 §11
Recording each apply's serial Not knowing which was the last good state The pipeline (below)
Scheduled detection of orphans and overlaps A small problem going twelve days undetected §5.2, §8.3
# Recording the serial, which costs four lines and is worth gold during
# a recovery: knowing which serial was the good one.
      - name: Record the state after applying
        if: always()
        run: |
          terraform state pull | jq '{
            serial, lineage,
            resources: (.resources | length),
            run: "${{ github.run_id }}",
            commit: "${{ github.sha }}",
            taken_at: (now | todate)
          }' | tee state-meta.json >> "$GITHUB_STEP_SUMMARY"

      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: state-meta-${{ inputs.environment }}-${{ github.run_id }}
          path: state-meta.json
          retention-days: 90

With this, the question "which was the last good state?" is answered by looking at the artefacts, not by guessing from file sizes.

  1. The "never do this" table

Never Why The safe alternative
terraform force-unlock without the five checks If the lock was real, you create the race condition the lock was preventing ci/check-lock.sh, and waiting if in doubt (§2)
terraform state push without a prior state pull It overwrites the remote without asking and with no way back A copy, verify lineage + serial + resources, push, plan (§4)
terraform state push -force It disables the only two protections the command has Raise the candidate's serial, which keeps the lineage check (§4.3)
terraform apply -lock=false You give up the only protection against state corruption -lock-timeout=10m (03-04)
Cancelling an apply from the CI's interface It leaves the state halfway, the lock orphaned and resources unrecorded Let it finish; if it is urgent, Ctrl-C once for an orderly stop
removed without lifecycle { destroy = false } when the resource must carry on existing It destroys it destroy = false, and verify the plan before applying (§8.4)
Importing without checking whether it is already in another state Overlapping states, which is the worst scenario ci/verify-import.sh first (§8.5)
Applying a migration whose plan is not zero It is the direct route to an overlap Stop and diagnose (07-05, §9.3)
ignore_changes = all It switches Terraform off for that resource while everybody believes it is managed Named attributes, with a comment and a review date (§7.3)
Relaunching a failed apply without verifying what was left It duplicates non-idempotent resources or deepens the divergence The procedure of §3
Deleting the old backend on the same day as migrating It removes the only route back Wait 7 days with the plan at zero (§9.3)
Recreating a data-bearing resource because the plan proposes it It creates the container empty and it looks as though it works Find out why it was deleted, and restore the data separately (§6.3)
Cleaning up before rotating a leaked secret The secret is still valid while you clean Rotate first, always (§10.2)
Deleting state versions "to tidy up" It destroys the recovery capability of §4 Rotate the secret; the history stops mattering (§10.2)

Common Mistakes and Tips

Forcing the unlock because "it has been ages". A Multi-AZ RDS apply legitimately takes forty minutes, and the apply_progress of 09-02 §9 proves it. Tip: check CloudTrail before deciding; the absence of writes over ten minutes is the proof, not the clock.

Forcing the unlock and considering the problem solved. The orphaned lock is the symptom; the interrupted apply is the disease. Tip: after every force-unlock with Operation: Apply, a mandatory plan -refresh-only.

Not writing down the serial and the lineage before touching anything. During a recovery they are the two numbers that decide whether a candidate version is the right one. Tip: terraform state pull | jq '{serial, lineage}' is the first command of every procedure in this lesson.

Choosing the S3 version by date. The last one before the incident may be the one written halfway through the apply that failed. Tip: look at the size. An abrupt drop is a truncation, and the lineage plus the resources confirm it.

Using state push -force to get around the serial error. It also disables the lineage check, which is what stops you writing another infrastructure's state. Tip: raise the candidate's serial with jq; the lineage check stays in place.

Relaunching the CI job after an interrupted apply. The retry will find AlreadyExists and fail, or create a duplicate if the name carries a random suffix. Tip: the plan-against-state-against-cloud comparison of §3.2 first, always.

Writing removed without destroy = false. A removed block destroys by default. In an overlap resolution that deletes infrastructure the other state believes it has. Tip: write the lifecycle before the from, and check the plan for delete before applying.

Treating a data-bearing orphan as junk. An "unused" bucket may be the destination of a quarterly report. Tip: tag it with PendingDeletion and a date, announce it, and delete a week later. A resource that has been there for months will survive seven more days.

Silencing drift with ignore_changes = all. The resource carries on appearing as managed and it no longer is. Tip: named attributes; and if you genuinely do not want to manage it, take it out of the state with removed, which is honest.

Dismissing a drift alert with a plausible explanation. In the chronology of §8.2, day 5's alert was the warning, and ignoring it cost twelve days and forty minutes of downtime. Tip: every unexpected drift is investigated until you find who caused it. "It'll be something from the migration" is not an explanation.

Applying a migration whose plan is not zero. It is the mistake that produces overlapping states. Tip: the zero plan is not just another check; it is the check. If it is not zero, stop.

Importing without checking whether it is already managed. It gives no error at all and it produces the worst possible scenario. Tip: ci/verify-import.sh as a mandatory step in the PR template.

Publishing the state or the plan JSON as an accessible artefact. They contain every value in the clear, including the sensitive ones. Tip: summaries extracted with jq, never the file.

Cleaning up before rotating a secret. Cleaning up takes hours; rotating, minutes; and in the meantime the secret is still valid. Tip: rotate, verify the shop is still up, and then clean up.

Exercises

Exercise 1: the 03:00 lock

You are woken up because prod's nightly deployment is failing:

╷
│ Error: Error acquiring the state lock
│
│ Lock Info:
│   ID:        7c4e1a90-2b56-4f83-9d17-e8a0c5f3b264
│   Path:      ecomarket-tfstate/ecomarket/prod/data/terraform.tfstate
│   Operation: OperationTypeApply
│   Who:       mlopez@mlopez-laptop
│   Version:   1.9.5
│   Created:   2026-09-23 02:41:08.117422 +0000 UTC
╵

It is 03:04 UTC. Marta is not answering her phone.

Questions:

  1. Read the block field by field. What does each one say and what worries you?
  2. What are the five checks, and how do you do them at three in the morning without Marta?
  3. Would you force it? Justify your answer with the data, not with the urgency.
  4. Suppose you force it and the subsequent plan -refresh-only shows that aws_db_instance.replica exists in AWS and not in the state. What is the complete sequence up to having it resolved?
  5. What would you change so that it does not happen again?

Exercise 2: the state that shrank

staging's plan fails:

╷
│ Error: Error loading state: unexpected end of JSON input
╵

Facts:

  • The ecomarket-tfstate bucket has versioning enabled.
  • The last successful apply was yesterday at 17:30, run 9156.
  • There was an apply at 02:14 this morning, run 9182, which the runner cancelled by timeout.
  • The artefact state-meta-staging-9156 says: {"serial": 1847, "lineage": "8f3a2b1c-4d5e-6f70-8192-a3b4c5d6e7f8", "resources": 43}.

Questions:

  1. What is the first action, before trying to recover anything?
  2. Write the commands to list the versions and explain what you are looking for in the output.
  3. Suppose you find four versions: 09-23 02:31 (31 KB), 09-23 02:21 (68 KB), 09-22 17:30 (68 KB), 09-22 11:47 (67 KB). Which do you choose and why? What do you do with the 02:21 one?
  4. Write the checks you would run on the candidate before the state push, and what you expect from each.
  5. After the push, the plan proposes 1 to add: aws_db_instance.replica. What does that mean and what do you do?
  6. The state push fails with "serial 1847 is older than remote 1850". What do you do, and what do you not do?

Exercise 3: the plans that contradict each other

On Monday morning two drift-detection alerts arrive:

--- infra/data (the old pipeline) ---
  # aws_security_group.db will be created
  # aws_db_subnet_group.main will be created
Plan: 2 to add, 0 to change, 0 to destroy.
--- live/staging/data (Terragrunt) ---
  # aws_lb.main will be destroyed
Plan: 0 to add, 0 to change, 1 to destroy.

staging's migration to Terragrunt was done twelve days ago.

Questions:

  1. What is happening, and why is it an emergency rather than a ticket?
  2. What is the very first action, before diagnosing anything?
  3. Write the diagnostic procedure: how do you determine exactly which resources are in both states?
  4. Write the block of code that removes the resources from the state that should not manage them, and explain the most dangerous line.
  5. What is the success criterion that says it is resolved?
  6. Three concrete measures so that it does not happen again in prod's migration, which is scheduled for a month's time.

Solutions

Solution 1

1. Reading field by field:

Field Value Reading
Operation OperationTypeApply The most worrying part. There may be a half-finished write
Who mlopez@mlopez-laptop A person, not a runner. It changes the whole analysis
Path .../prod/data/... The production database. The most delicate component
Created 02:41, 23 minutes ago A grey area: neither clearly alive nor clearly dead
Version 1.9.5 It matches CI. There is no version divergence

The combination person + apply + prod/data + 23 minutes is the worst possible. A cancelled ephemeral runner is easy to rule out; a laptop is not. Marta could have the apply running while her phone is on silent.

2. The five checks without Marta:

# 1. The exact age.
date -u +%Y-%m-%dT%H:%M:%SZ        # 03:04 vs 02:41 → 23 minutes

# 2. Is there a CI job? (rules out the lock belonging to the pipeline)
gh run list --repo ecomarket/ecomarket-infra --status in_progress --limit 10

# 3. THE DECISIVE CHECK: has prod's apply role written anything
#    in the last 10 minutes?
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=Username,AttributeValue=ecomarket-terraform-prod \
  --start-time "$(date -u -d '15 minutes ago' +%Y-%m-%dT%H:%M:%SZ)" \
  --query 'Events[].{time:EventTime,event:EventName}' --output table

# 3b. And also under Marta's identity, because from her laptop
#     she may be using her own role.
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=Username,AttributeValue=mlopez \
  --start-time "$(date -u -d '30 minutes ago' +%Y-%m-%dT%H:%M:%SZ)" \
  --query 'Events[].{time:EventTime,event:EventName}' --output table

# 4. Is anything being modified in RDS right now?
aws rds describe-db-instances \
  --query 'DBInstances[?starts_with(DBInstanceIdentifier, `ecomarket-prod`)].{id:DBInstanceIdentifier,status:DBInstanceStatus}' \
  --output table

# 5. A backup (even though I cannot do state pull with the lock
#    in place, I can download the object from S3 directly).
aws s3 cp s3://ecomarket-tfstate/ecomarket/prod/data/terraform.tfstate \
  "/tmp/state-prod-data-$(date +%s).json"
jq '{serial, lineage, resources: (.resources|length)}' /tmp/state-prod-data-*.json

Step 5 deserves a note: with the state locked you cannot do terraform state pull, but you can download the object from S3 with the AWS CLI. The lock is a Terraform convention over DynamoDB, not an S3 permission. It is exactly why the plan role needs s3:GetObject on the state bucket.

3. Force it?

It depends on the result of check 3, and only on that. Two scenarios:

If CloudTrail shows... Decision Reason
Writes up to 1-2 minutes ago Do NOT force There is a live apply. Forcing on prod/data while a database is being modified is how a state gets corrupted
The last write at 02:43, nothing after Force it, after step 5 and with a notification The process wrote for two minutes and stopped. Twenty-one minutes of silence during an apply operation is a dead process
No writes at all Force it, and note that the apply never did anything The lock was taken and the process died before writing

And the part that is not technical: even if CloudTrail says it is dead, with a Who belonging to a person you have to escalate, not just try the phone. A message in the team channel, the on-call lead, and a written record of the decision with the data that supports it. The cost of waiting another twenty minutes is a delayed deployment; the cost of forcing on a live apply in prod/data is a corrupt state on the production database at three in the morning.

4. The sequence with the orphaned replica:

# a. Confirm that it exists and in what state.
aws rds describe-db-instances \
  --db-instance-identifier ecomarket-prod-db-replica \
  --query 'DBInstances[0].{status:DBInstanceStatus,created:InstanceCreateTime}'
# b. An import block, reviewable in a PR (06-04).
# infra/data/imports.tf
# TEMPORARY — mlopez's apply of 2026-09-23 02:41 created the replica and
# died before saving it. Incident: docs/incidents/2026-09-23-lock-prod-data.md
import {
  to = aws_db_instance.replica
  id = "ecomarket-prod-db-replica"
}
# c. Verify that the import leaves the resource as no-op.
terraform plan -out=recovery.tfplan
terraform show -json recovery.tfplan \
  | jq -r '.resource_changes[] | select(.address == "aws_db_instance.replica")
           | "\(.address): \(.change.actions | join(","))"'
# Expected: no-op.
# If it says "update": look at what changes before applying.
# If it says "delete,create": STOP. You do not replace a prod replica.

# d. Apply.
terraform apply recovery.tfplan

# e. Remove the import block (it has served its purpose) in the same PR
#    or the next one, and document the incident.

5. What to change:

Change What it prevents
Ban apply in prod from laptops. Only the pipeline, with the apply role The root cause: a manual production apply in the small hours
An IAM policy that only allows assuming ecomarket-terraform-prod from GitHub's OIDC It makes the previous ban technical, not merely documentary
timeouts { create = "90m" } on aws_db_instance.replica and timeout-minutes: 120 on the job A legitimate apply being cut off by time
A documented on-call role with an alternative phone number The decision depending on somebody picking up their mobile
ci/check-lock.sh in the repository, runnable from memory Having to improvise the commands at 3 in the morning

The first is the one that really matters: the incident was not caused by the lock, it was caused by production being appliable from a laptop.

Solution 2

1. The first action: copy the corrupt state before touching it.

aws s3 cp s3://ecomarket-tfstate/ecomarket/staging/data/terraform.tfstate \
  "/tmp/CORRUPT-staging-data-$(date +%Y%m%d-%H%M%S).json"

It looks useless because it is broken, and it is not: a truncation preserves most of the resources, and if all three recovery routes fail, that file is the source for rebuilding by hand.

2. Listing the versions:

aws s3api list-object-versions \
  --bucket ecomarket-tfstate \
  --prefix ecomarket/staging/data/terraform.tfstate \
  --query 'Versions[].{date:LastModified,size:Size,version:VersionId}' \
  --output table

What I look for, in this order: first the size, because an abrupt drop betrays the truncation; then the date, to place it relative to the failed apply at 02:14; and only then do I download candidates to check serial and lineage.

3. The choice:

Version Size Reading
09-23 02:31 31 KB The corrupt one. Less than half: it is the truncated write of the apply that died
09-23 02:21 68 KB Written during the failed apply. Normal size, but it is an intermediate state
09-22 17:30 68 KB The main candidate: the last known successful apply (run 9156)
09-22 11:47 67 KB Earlier. Discarded unless the previous one fails

I choose the 09-22 17:30 one, because it is the only one corresponding to a completed apply and the one whose metadata I have on record (serial 1847, 43 resources).

What I do with the 02:21 one: I do not discard it, I inspect it. It is a valid intermediate state of the apply that failed, and it tells me how far it got before dying:

aws s3api get-object --bucket ecomarket-tfstate \
  --key ecomarket/staging/data/terraform.tfstate \
  --version-id 8vR4tY7wL1zB3c /tmp/intermediate.json

# Which resources did it know about that the 17:30 one does not?
comm -13 \
  <(jq -r '.resources[] | "\(.type).\(.name)"' /tmp/candidate-1730.json | sort) \
  <(jq -r '.resources[] | "\(.type).\(.name)"' /tmp/intermediate.json | sort)

That list is exactly the inventory of possible orphans: resources the apply created and that the version I am about to restore does not know about. It is worth gold and it comes free.

4. The checks before the push:

aws s3api get-object --bucket ecomarket-tfstate \
  --key ecomarket/staging/data/terraform.tfstate \
  --version-id <the-1730-one> /tmp/candidate.json

# C1. Is it valid JSON?
jq empty /tmp/candidate.json && echo "✓ Valid JSON"
# Expected: valid. If not, that version is damaged too.

# C2. The same lineage as the one on record? THE CRITICAL CHECK.
[[ "$(jq -r .lineage /tmp/candidate.json)" == "8f3a2b1c-4d5e-6f70-8192-a3b4c5d6e7f8" ]] \
  && echo "✓ lineage correct" || { echo "STOP: a different infrastructure"; exit 1; }
# Expected: it matches. If not, it is another thing's state and pushing it
# would propose destroying the whole of staging.

# C3. Is the serial the expected one?
jq -r .serial /tmp/candidate.json
# Expected: 1847, the one from run 9156's artefact.

# C4. Are all 43 resources there?
jq '.resources | length' /tmp/candidate.json
# Expected: 43. Fewer means it is an older version than I think.

# C5. Which resources are they? A quick look in case something obvious is missing.
jq -r '.resources[] | "\(.type).\(.name)"' /tmp/candidate.json | sort | head -20

5. If the plan proposes 1 to add: aws_db_instance.replica:

It means the replica was created during the failed apply at 02:14, after the version I have restored. The restored state does not know about it, but it exists in AWS: it is an orphaned resource (§5).

# Confirm that it exists:
aws rds describe-db-instances \
  --db-instance-identifier ecomarket-staging-db-replica \
  --query 'DBInstances[0].DBInstanceStatus'
  • If it exists: import it, do not apply. Applying would try to create a second replica or fail with AlreadyExists. And the list of possible orphans I produced in point 3 had already told me this was coming.
  • If it does not exist: the apply died before creating it. Applying is correct.

6. If the state push fails on the serial:

Error: Failed to write state: cannot import state with serial 1847 over newer state with serial 1850

What I do NOT do: terraform state push -force. It would also disable the lineage check, which is the only thing that stops me writing another infrastructure's state, and it is precisely what protects me most right now.

What I do: raise the candidate's serial, keeping everything else.

REMOTE=$(jq -r .serial /tmp/CORRUPT-staging-data-*.json 2>/dev/null || echo 1850)
jq --argjson s $((REMOTE + 1)) '.serial = $s' /tmp/candidate.json > /tmp/candidate-ok.json

# Verify that only the serial changed:
diff <(jq -S 'del(.serial)' /tmp/candidate.json) \
     <(jq -S 'del(.serial)' /tmp/candidate-ok.json) \
  && echo "✓ only the serial changed"

terraform state push /tmp/candidate-ok.json

The diff with del(.serial) is the check that turns a manual edit of the state into an auditable operation: it proves nothing else was touched.

Solution 3

1. What is happening and why it is an emergency.

Two states are managing the same staging infrastructure. The old pipeline (infra/data) wants to create resources that exist but are no longer in its state; the new one (live/staging/data) wants to destroy a load balancer that exists and works.

It is an emergency rather than a ticket for three reasons:

  1. It is live. Both pipelines are still scheduled. Whichever runs next modifies real infrastructure.
  2. One of the actions is destructive. aws_lb.main will be destroyed takes staging down the moment it is applied.
  3. It gets worse on its own. Every run increases the divergence between the two states and makes it harder to determine which is the legitimate owner of what.

The unmistakable signal is the contradiction: two states proposing opposite actions on the same infrastructure.

2. The very first action: stop both pipelines.

gh workflow disable terraform-apply.yml --repo ecomarket/ecomarket-infra
gh workflow disable terragrunt-apply.yml --repo ecomarket/ecomarket-infra

# And announce it in the team channel: nobody applies anything in staging
# until further notice.

Before diagnosing, before understanding, before copying states. Every minute with the pipelines enabled is a chance that one runs and destroys something.

3. The diagnosis:

# a. A copy of BOTH states.
terraform -chdir=infra/data state pull > /tmp/state-old.json
terragrunt -chdir=live/staging/data state pull > /tmp/state-new.json

for f in old new; do
  echo "--- ${f} ---"
  jq '{serial, lineage, resources: (.resources|length)}' "/tmp/state-${f}.json"
done

What I expect to see: different lineages. That is the confirmation that these are two independent states and not two views of the same one. If the lineage were the same, the problem would be a different one (a copy of the same state in two places).

# b. The real identifiers in each one.
for f in old new; do
  jq -r '.resources[].instances[].attributes | (.arn // .id // empty)
         | select(startswith("arn:") or startswith("sg-") or startswith("vpc-")
                  or startswith("subnet-") or startswith("i-"))' \
    "/tmp/state-${f}.json" | sort -u > "/tmp/ids-${f}.txt"
done

echo "=== IN BOTH: the overlap ==="
comm -12 /tmp/ids-old.txt /tmp/ids-new.txt | tee /tmp/overlapping.txt
wc -l /tmp/overlapping.txt

echo "=== Only in the old one ==="
comm -23 /tmp/ids-old.txt /tmp/ids-new.txt

echo "=== Only in the new one ==="
comm -13 /tmp/ids-old.txt /tmp/ids-new.txt
# c. Translate each overlapping ARN into its address in each state, which is
#    what I need in order to write the removed blocks.
while read -r arn; do
  echo "=== ${arn}"
  for f in old new; do
    ADDR=$(jq -r --arg a "$arn" \
      '.resources[] | . as $r | .instances[]
       | select((.attributes.arn // .attributes.id) == $a)
       | "\($r.module // "root").\($r.type).\($r.name)"' \
      "/tmp/state-${f}.json" 2>/dev/null | head -1)
    echo "    ${f}: ${ADDR:-(not present)}"
  done
done < /tmp/overlapping.txt
# d. And the REAL DUPLICATES: resources created twice under different
#    names. They are the collateral damage of the failed migration.
aws elbv2 describe-load-balancers \
  --query 'LoadBalancers[?starts_with(LoadBalancerName, `ecomarket-staging`)].{name:LoadBalancerName,created:CreatedTime,arn:LoadBalancerArn}' \
  --output table

If two staging load balancers show up, you have to decide which one stays — the one whose DNS the domain points at — and delete the other.

4. The removed blocks:

The decision: the new state (Terragrunt) is the migration's destination, so it is the owner. The old one must forget the overlapping resources.

# infra/data/removed.tf
#
# Resolution of the state overlap detected on 2026-09-23.
# These resources move to being managed from live/staging/data (Terragrunt),
# which is the destination of migration INFRA-4712.
#
# THE RESOURCES STILL EXIST. They are only removed from THIS state.
# Incident: docs/incidents/2026-09-23-overlap-staging.md

removed {
  from = aws_security_group.db
  lifecycle { destroy = false }
}

removed {
  from = aws_db_subnet_group.main
  lifecycle { destroy = false }
}

removed {
  from = aws_db_instance.main
  lifecycle { destroy = false }
}

removed {
  from = aws_lb.main
  lifecycle { destroy = false }
}

The most dangerous line is lifecycle { destroy = false }, and it is dangerous by omission: if it is missing, the removed block destroys the resource. In this context that means deleting staging's load balancer and database that the other state believes it is managing, leaving that state with phantom resources and the environment down.

# The MANDATORY check before applying:
terraform -chdir=infra/data plan -out=cleanup.tfplan

terraform -chdir=infra/data show -json cleanup.tfplan \
  | jq -r '.resource_changes[]
           | select(.change.actions | contains(["delete"]))
           | "WOULD DESTROY: \(.address)"'

If that query returns a single line, you do not apply: a destroy = false is missing somewhere. A correct removed produces resources that "will no longer be managed by Terraform", never destroyed resources.

5. The success criterion:

terraform -chdir=infra/data apply cleanup.tfplan

# BOTH states at zero changes. Not one: both.
terraform -chdir=infra/data plan -detailed-exitcode \
  && echo "✓ old state: no changes"

terragrunt -chdir=live/staging/data plan -detailed-exitcode \
  && echo "✓ new state: no changes"

# And no overlap:
ci/detect-overlap.sh staging            # must return nothing

# And the shop up:
curl -sf https://staging.ecomarket.example.com/health | jq .

All four at once. The new one giving zero is not enough: if the old one carries on proposing to create resources, the overlap persists in the other direction and it will be back next Monday.

6. The three measures for prod's migration:

Measure 1: disable the old pipeline BEFORE migrating, not after.

# The first PR of prod's migration touches no .tf at all.
# Only this:
on:
  push:
    branches: [main]
    paths:
      - 'infra/network/**'
      - 'infra/app/**'
      # infra/data/ REMOVED: being migrated to Terragrunt (INFRA-4712).
      # Re-enable only if the migration is aborted.

It is mistake 2 of the chronology of §8.2, and the cheapest to fix: a single PR, before anything is touched.

Measure 2: the zero plan as an automatic gate, not a human judgement.

#!/usr/bin/env bash
# ci/migrate-verified.sh — the migration does NOT continue if the plan is not zero.
set -euo pipefail

echo "=== Before: an inventory of the source state ==="
BEFORE=$(terraform -chdir="$SOURCE" state list | wc -l)
LINEAGE=$(terraform -chdir="$SOURCE" state pull | jq -r .lineage)

echo "=== Migrate ==="
terragrunt -chdir="$TARGET" init --terragrunt-non-interactive

echo "=== THE GATE: the target's plan must give ZERO ==="
if ! terragrunt -chdir="$TARGET" plan -detailed-exitcode; then
  echo
  echo "ABORTED: the plan proposes changes."
  echo "A plan that is not zero in a migration means the new state"
  echo "does NOT know the existing infrastructure. Applying would produce"
  echo "duplicated resources and overlapping states."
  echo "See module 9, lesson 3, §8."
  exit 1
fi

echo "=== Verify the count and the lineage ==="
AFTER=$(terragrunt -chdir="$TARGET" state list | wc -l)
[[ "$BEFORE" == "$AFTER" ]] || { echo "ABORTED: ${BEFORE} != ${AFTER}"; exit 1; }

echo "✓ Migration verified. The source backend is kept for 7 days."

The difference from what happened: the script aborts. It does not ask anybody whether they want to carry on "to see if it sorts itself out".

Measure 3: permanent overlap detection in the pipeline, from day one.

# .github/workflows/state-integrity.yml
name: State integrity

on:
  schedule:
    - cron: '0 7 * * *'          # daily, not weekly: during a migration
                                 # twelve days is an eternity
  workflow_dispatch:

jobs:
  overlap:
    strategy:
      fail-fast: false
      matrix:
        environment: [dev, staging, prod]
    runs-on: ubuntu-latest
    permissions: { id-token: write, contents: read }
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::${{ vars[format('ACCOUNT_{0}', matrix.environment)] }}:role/ecomarket-terraform-plan-${{ matrix.environment }}
          aws-region: eu-west-1

      - id: check
        run: |
          ci/detect-overlap.sh ${{ matrix.environment }} | tee overlap.txt
          [[ ! -s overlap.txt ]]
        continue-on-error: true

      - if: steps.check.outcome == 'failure'
        run: |
          gh issue create --repo ${{ github.repository }} \
            --title "URGENT: state overlap in ${{ matrix.environment }}" \
            --label "urgent,incident" \
            --assignee "@ecomarket/platform" \
            --body-file overlap.txt
          # And disable that environment's apply pipelines,
          # because every run can destroy infrastructure.
          gh workflow disable terraform-apply.yml --repo ${{ github.repository }}
          gh workflow disable terragrunt-apply.yml --repo ${{ github.repository }}
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

The design decision that matters: the check disables the apply pipelines when it detects an overlap. It is aggressive, and it is correct. An undetected overlap is an incident waiting to happen; a pipeline disabled by mistake is a ten-minute inconvenience. The asymmetry justifies the aggression.

And measure zero, which is not a configuration one: day 5's drift alert gets investigated. "It'll be something from the migration" is not an explanation, it is an unchecked hypothesis, and in this story it cost forty minutes of staging being down.

Conclusion

This lesson has been a manual of procedures, and its thesis is that state problems are not solved with more knowledge of Terraform, but with verification discipline.

  • The six problems have an inverse relationship between frequency and severity. The orphaned lock happens every week and is of low severity; overlapping states happen once and can bring an environment down. That is why the learning order follows frequency and the prevention order follows severity.
  • Before touching any state, terraform state pull | jq '{serial, lineage}'. Those two numbers are the state's identity and they are what decides, during a recovery, whether a candidate version is the right one or belongs to another infrastructure.
  • A force-unlock is decided with CloudTrail, not with the clock. The Operation field says whether the risk is low or high, Who says whether there is anybody to ask, and the absence of writes by the apply role over ten minutes is the only reasonable proof that the process died. And forcing is not the end: if the operation was Apply, a mandatory plan -refresh-only says what was left halfway.
  • Terraform writes the state after every resource, not at the end. That is why an interrupted apply preserves almost all the progress, and why the only genuinely problematic resource is the one that was in flight: the orphan candidate. Comparing the approved plan, terraform state list and the cloud closes the diagnosis in three commands.
  • For a corrupt state there are three routes in order: the local .tfstate.backup, S3 versioning and rebuilding by importing. The second is the one you will use, and it works only if somebody enabled versioning before the incident. The abrupt drop in size betrays the truncated version, and the lineage is the check that saves your life: a different lineage means a different infrastructure, and pushing it would propose destroying the whole thing.
  • state push overwrites without asking, and -force disables its only two protections. When the serial is in the way, raise it with jq and prove with a diff that you touched nothing else: that keeps the lineage check and turns a manual edit into an auditable operation.
  • Orphaned resources are detected by comparing two lists, and that is possible because local.common_tags puts ManagedBy = "terraform" on everything. A naming convention that looked cosmetic in module 7 turns out to be this module's detection infrastructure.
  • The Atlantis PR closed after applying produces the inverse orphan: resources in the state and not in the code, which main's next apply will destroy with nobody expecting it. It is detected with a check when the PR closes, and resolved either by merging the PR or by destroying deliberately, never by letting it be.
  • Persistent drift is almost always normalisation, and the 1024 -> 1024 diff is its signature. ignore_changes is the legitimate answer when another system manages that attribute — autoscaling, the application's pipeline — but only with named attributes. ignore_changes = all stabilises nothing: it switches Terraform off for that resource while everybody believes it is managed.
  • Overlapping states are the worst scenario and they arrive by two routes: a migration whose plan was not zero and was applied anyway, and a duplicated import that Terraform accepts without a word. The resolution starts by stopping every pipeline and ends with both states at zero changes; and removed without lifecycle { destroy = false } turns the resolution into the disaster you were trying to avoid.
  • For a leaked secret, you rotate first. Cleaning up takes hours and rotating takes minutes, and while you clean the secret is still valid. A rotated secret in an old state stops being a secret, and that makes it unnecessary to destroy the history that is your recovery capability.
  • And prevention fits into six measures, five of them configuration: versioning and a cross-region copy of the state bucket, locking, separation by component, cancel-in-progress: false on the apply, recording each deployment's serial, and scheduled detection of orphans and overlaps. The sixth is not technical: do not cancel an apply from the CI's interface, which is the one-click gesture that originates half the incidents in this lesson.

One last situation remains, and it is the one this module has not yet covered. You have read the whole error message. You have walked the diagnostic method. You have generated the trace, filtered it down to the twelve lines that matter, checked the provider's schema, isolated the module in a minimal directory. You have checked the state, the lock, the lineage. And the error is still there, and it does not appear in the documentation, and it makes no sense.

That moment arrives, and it arrives more often than people admit. The skill you need then is not a technical one: it is knowing where to ask, how to ask and what you need to provide so that somebody with the necessary context can help you — or so that the maintainer who can genuinely fix it has something in their hands that they can run.

The module's last lesson, Community and Support, is that map: how to read the official documentation and the provider's CHANGELOG properly, how to search for an error effectively by quoting the stable part of the message, where to look depending on the kind of problem, how to tell whether the bug is core's or the provider's, the complete template of a reproducible report — with the secret-scrubbed log this lesson and the previous one have taught you to produce — what makes an issue get closed with no answer, how to contribute back, what OpenTofu is and what migrating involves, when commercial support is worth it, and EcoMarket's update policy as a worked example of how a team stays current without things blowing up.

© Copyright 2026. All rights reserved