The previous lesson ended by acknowledging a limit: that whole catalogue assumes the error message tells you something. Sometimes it does not. The apply fails with a generic provider error, or it sits there for twelve minutes without saying why, or the plan announces that it is going to replace the production database and there is no obvious way to find out which attribute causes it. That is where reading messages ends and instrumentation begins.

This lesson is the toolbox. It adds no new errors to the catalogue: it adds ways of looking. And it has a specific thread running through it, which is the debt module 8 left behind: learning to read a 4,000-line trace without drowning in it. That log exists, TF_LOG=TRACE produces it, and the difference between someone who can debug Terraform and someone who cannot is that the first knows that only twelve of those 4,000 lines matter, and knows how to get to them in three commands.

The order of the lesson is deliberate and it reflects the order in which the tools are really used: first the ones that do not require running anything dangerous (console, the plan in JSON, providers schema), and only then the heavy artillery (TF_LOG=TRACE, graph, probes). Anyone who starts with TF_LOG=TRACE loses half an hour reading lines that have nothing to do with their problem.

A security warning, and it is the most important one in the whole module. Terraform's debug traces contain complete HTTP request and response bodies: your resources' values, the authentication headers (signed, but revealing), the account identifiers, and, with certain providers and certain resources, sensitive values in the clear. A TF_LOG=TRACE log of an apply that creates a database may contain the password. You never paste a debug log into a public issue, a company chat or a ticket without scrubbing it first. This lesson devotes a whole section to that procedure, and 09-04 picks it up again when talking about reporting bugs.

  1. The right order for the tools

Before the detail, the map. Each tool answers one class of question, and using the wrong one costs time.

flowchart TD
    A["Something is wrong"] --> B{"What kind of<br/>question do I have?"}

    B -->|"'What does this<br/>expression evaluate to?'"| C["terraform console<br/>§7"]
    B -->|"'Why is it replacing<br/>this resource?'"| D["show -json + jq<br/>replace_paths<br/>§8"]
    B -->|"'What is unknown<br/>and why?'"| E["show -json + jq<br/>after_unknown<br/>§8"]
    B -->|"'Does this attribute exist<br/>in my version?'"| F["providers schema -json<br/>§12"]
    B -->|"'Why is there a cycle?'"| G["terraform graph<br/>§10"]
    B -->|"'Which code is actually<br/>running?'"| H["modules.json<br/>§13"]
    B -->|"'What does Terraform ask<br/>the API, and what comes back?'"| I["TF_LOG + filtering<br/>§2-§5"]
    B -->|"'Terraform has hung /<br/>has crashed'"| J["TF_LOG=TRACE, crash.log<br/>§5, §15"]

    C --> K["Cheap: runs nothing"]
    D --> K
    E --> K
    F --> K
    G --> K
    H --> K
    I --> L["Expensive: generates megabytes<br/>and can leak secrets"]
    J --> L

    style K fill:#dcfce7,stroke:#15803d
    style L fill:#fef3c7,stroke:#b45309

The rule: exhaust the green column before you touch the amber one. 70% of Terraform problems are solved with console, the plan in JSON and providers schema, which run nothing, write nothing and leak nothing.

  1. TF_LOG: levels and what each one contributes

TF_LOG is an environment variable that switches on debug logging. It has no command-line flag equivalent, and its value is one of five levels (plus JSON, which we will come to).

TF_LOG=DEBUG terraform plan
Level Typical volume (EcoMarket plan, 60 resources) What it contributes When to use it
ERROR ~5 lines Only what you already see in the normal output Practically never; it adds nothing
WARN ~20 lines Internal warnings: deprecated providers, ignored fields Rarely
INFO ~80 lines Version, CLI arguments, chosen backend, providers launched To confirm what is being run: version, backend, plugins
DEBUG ~3,000 lines The above plus the provider's HTTP requests and responses, refresh decisions The working level. It covers 90% of real needs
TRACE ~45,000 lines The above plus a vertex-by-vertex walk of the graph, expression evaluation, internal RPCs Cycles, hangs, inexplicable unknown values, core bugs

Two observations that save time:

DEBUG is almost always the right level. It is where the HTTP calls appear, which is what 90% of diagnoses need. TRACE multiplies the volume by fifteen and adds information about Terraform's engine, not about what it asks the cloud for. If your question is "what does Terraform ask AWS for", DEBUG answers it; if your question is "why does Terraform think this resource depends on that one", you need TRACE.

The volume grows with the size of the state, not with the size of the problem. A TF_LOG=TRACE over EcoMarket's prod state produces tens of thousands of lines even if the failure involves a single resource. That is why §5 is not optional: without a filtering technique, TRACE is unusable.

# A quick check: which version, which backend, which providers.
# It costs nothing and answers three of the questions of 09-01 §4.
TF_LOG=INFO terraform plan 2>&1 | grep -E "Terraform version|Go runtime|backend|Starting provider"
2026-09-23T08:14:22.481Z [INFO]  Terraform version: 1.9.5
2026-09-23T08:14:22.482Z [INFO]  Go runtime version: go1.22.4
2026-09-23T08:14:22.483Z [INFO]  CLI args: []string{"terraform", "plan"}
2026-09-23T08:14:22.601Z [INFO]  backend/local: starting Plan operation
2026-09-23T08:14:22.612Z [INFO]  provider: configuring client automatic mTLS
2026-09-23T08:14:22.789Z [INFO]  provider.terraform-provider-aws_v5.62.0_x5: configuring server automatic mTLS

Six lines that confirm the Terraform version, the exact provider version and that the backend started. It is the most useful TF_LOG and the least well known.

TF_LOG=JSON

There is a sixth value that emits the lines as JSON instead of text:

TF_LOG=JSON terraform plan 2>traces.json
{"@level":"debug","@message":"Received request","@module":"sdk.proto","@timestamp":"2026-09-23T08:14:25.102Z","tf_provider_addr":"registry.terraform.io/hashicorp/aws","tf_req_id":"b1f4a2c7-8e91-4d63-a5f0-2c8b7e91d340","tf_resource_type":"aws_db_instance","tf_rpc":"PlanResourceChange"}

It is equivalent to TRACE in volume, but each line is an object you can query with jq. For the funnel of §5 it is noticeably more convenient than text:

# With JSON, filtering by resource is trivial and exact.
jq -r 'select(.tf_resource_type == "aws_db_instance")
       | "\(.["@timestamp"]) \(.tf_rpc // "-") \(.["@message"])"' traces.json

  1. TF_LOG_CORE, TF_LOG_PROVIDER and TF_LOG_PATH

Terraform is split into two processes that talk to each other over gRPC: the core (the terraform binary, which evaluates the HCL, builds the graph and computes the plan) and the provider (a separate binary, terraform-provider-aws_v5.62.0_x5, which talks to the API). Each has its own log level.

Variable Controls Practical effect
TF_LOG Both at once The hammer. If you specify nothing more, this is what happens
TF_LOG_CORE Core only Graph, expression evaluation, unknown values, state
TF_LOG_PROVIDER Provider only HTTP requests, retries, the resources' logic

The use that really changes things is halving the noise depending on what you are looking for:

# Case A: "what does the provider ask AWS for?"
# Core quiet; provider at full volume.
TF_LOG_CORE=INFO TF_LOG_PROVIDER=TRACE terraform apply 2>provider-trace.log

# Case B: "why does Terraform think this value is unknown?"
# Provider quiet; core at full volume.
TF_LOG_CORE=TRACE TF_LOG_PROVIDER=ERROR terraform plan 2>core-trace.log

In an EcoMarket plan with 60 resources, case B cuts the log from 45,000 lines to around 11,000 (core only), and case A to around 18,000 (provider only). It is still a lot, but it is half the problem eliminated up front.

TF_LOG_PATH

The logs go to stderr, mixed in with Terraform's normal output. TF_LOG_PATH diverts them to a file:

TF_LOG=DEBUG TF_LOG_PATH=/tmp/ecomarket-plan.log terraform plan

Three properties worth knowing:

  1. The on-screen output becomes readable again. You see the normal plan, with no traces interleaved.
  2. The file is opened in append mode. Two consecutive runs write into the same file, one after the other. If you are not expecting that, you end up debugging the run from twenty minutes ago. Delete it between attempts.
  3. The directory must exist. Terraform does not create it and fails at startup if it cannot write.
# The pattern I always use: one file per attempt, with a timestamp,
# in a throwaway directory.
mkdir -p /tmp/tf-debug
export TF_LOG=DEBUG
export TF_LOG_PATH="/tmp/tf-debug/plan-$(date +%Y%m%d-%H%M%S).log"
terraform plan
echo "Trace at: ${TF_LOG_PATH} ($(wc -l < "${TF_LOG_PATH}") lines)"

Warning. /tmp/tf-debug/ now contains files holding your cloud's request bodies. On your laptop, delete them when you are done. On an ephemeral runner they disappear on their own; on a persistent Jenkins agent (08-02), they do not: use a directory inside the job's workspace, which CI itself cleans up.

  1. Anatomy of a log line and the lifecycle of a provider call

4.1. The line

2026-09-23T08:14:25.102Z [DEBUG] provider.terraform-provider-aws_v5.62.0_x5: Received request: tf_rpc=PlanResourceChange tf_resource_type=aws_db_instance tf_req_id=b1f4a2c7-8e91-4d63-a5f0-2c8b7e91d340 @module=sdk.proto timestamp=2026-09-23T08:14:25.102Z
Field Value What it is for when debugging
Timestamp 2026-09-23T08:14:25.102Z Measuring gaps. A 90-second jump between two lines is where it hangs
Level [DEBUG] Filtering
Origin provider.terraform-provider-aws_v5.62.0_x5 Core or provider, and exactly which version of the provider
Message Received request The event
tf_rpc PlanResourceChange The lifecycle phase. It is the most useful field of the lot (§4.2)
tf_resource_type aws_db_instance Which resource type. For filtering by the one that fails
tf_req_id b1f4a2c7-... Correlates request and response. grepping this ID isolates a complete operation
@module sdk.proto The internal layer. sdk.proto is the gRPC boundary; aws is the provider's logic

The two fields that do the work are tf_req_id and the timestamp. The first turns an interleaved log — ten resources being processed in parallel — into separable threads. The second tells you where the time is going.

4.2. The lifecycle of a provider call

Terraform and the provider talk to each other with a small set of gRPC calls. Knowing them is what lets you tell at which point something failed:

sequenceDiagram
    participant N as Terraform core
    participant P as Provider (separate process)
    participant A as AWS API

    N->>P: GetProviderSchema
    Note over P: Returns ALL resource types<br/>and their attributes. Slow: it is cached

    N->>P: ValidateProviderConfig
    N->>P: ConfigureProvider
    Note over P,A: Credentials and region are resolved here.<br/>A failure HERE affects EVERYTHING

    loop For every resource in state
        N->>P: ReadResource
        P->>A: Describe... (read)
        A-->>P: real state
        P-->>N: updated state
        Note over N: This is the REFRESH.<br/>Drift is detected here
    end

    loop For every resource with changes
        N->>P: PlanResourceChange
        P-->>N: proposed plan + unknown values
        Note over N: This is where "(known after apply)" is born
    end

    Note over N: — The user approves —

    loop For every action in the plan
        N->>P: ApplyResourceChange
        P->>A: Create/Update/Delete
        A-->>P: result
        P-->>N: new state
        Note over N: Consistency is checked here:<br/>"inconsistent result after apply"
    end

The symptom → RPC translation table, which is what you will actually use:

Symptom RPC to look at What to look for
Fails right at the start, before the plan ConfigureProvider Credentials, region, custom endpoints
"Terraform says something changed that I did not change" ReadResource The API's response against the stored state
An unexpected (known after apply) PlanResourceChange What the provider returns as unknown
Provider produced inconsistent final plan PlanResourceChange → ApplyResourceChange Compare the proposed plan with the result
The apply hangs ApplyResourceChange The time gap between two lines
A data returns something odd ReadDataSource The arguments it was called with
An Unsupported argument you believe is valid GetProviderSchema Confirm the binary's version (§12 is more convenient)

4.3. Finding the HTTP request that fails

The AWS provider logs every request and every response with very recognisable markers:

2026-09-23T08:14:25.310Z [DEBUG] provider.terraform-provider-aws_v5.62.0_x5: [DEBUG] AWS API Request Details
---[ REQUEST POST-SIGN ]-----------------------------
POST /  HTTP/1.1
Host: rds.eu-west-1.amazonaws.com
User-Agent: aws-sdk-go-v2/1.30.3 APN/1.0 HashiCorp/1.0 Terraform/1.9.5
Content-Length: 412
Authorization: AWS4-HMAC-SHA256 Credential=ASIAX3EXAMPLE/20260923/eu-west-1/rds/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date;x-amz-security-token, Signature=8f3a...
Content-Type: application/x-www-form-urlencoded; charset=utf-8
X-Amz-Date: 20260923T081425Z
X-Amz-Security-Token: IQoJb3JpZ2luX2VjE...

Action=CreateDBInstance&AllocatedStorage=500&BackupRetentionPeriod=30&DBInstanceClass=db.r6g.xlarge&DBInstanceIdentifier=ecomarket-prod-db-noble-bee&Engine=postgres&EngineVersion=16.9&MasterUsername=ecomarket&MasterUserPassword=REDACTED&MultiAZ=true&Version=2014-10-31
-----------------------------------------------------
2026-09-23T08:14:26.847Z [DEBUG] provider.terraform-provider-aws_v5.62.0_x5: [DEBUG] AWS API Response Details
---[ RESPONSE ]--------------------------------------
HTTP/1.1 400 Bad Request
Content-Length: 297
Content-Type: text/xml
Date: Wed, 23 Sep 2026 08:14:26 GMT
X-Amzn-Requestid: 4c0e2f1a-9b77-4d31-8e5c-6f2a91d0b3e8

-----------------------------------------------------
<ErrorResponse xmlns="http://rds.amazonaws.com/doc/2014-10-31/">
  <Error>
    <Type>Sender</Type>
    <Code>InvalidParameterValue</Code>
    <Message>Cannot find version 16.9 for postgres</Message>
  </Error>
  <RequestId>4c0e2f1a-9b77-4d31-8e5c-6f2a91d0b3e8</RequestId>
</ErrorResponse>

This is exactly what you are looking for and what justifies the whole chapter. The request body tells you what Terraform actually sent, and very often that is not what you thought you had written. And the response gives you the API's complete message, which is frequently more explicit than the one that arrives wrapped inside the error message.

Notice a detail in the example: MasterUserPassword=REDACTED. The AWS provider substitutes some known sensitive fields. Some, not all. An EC2 user_data goes through in the clear, and that is where EcoMarket puts the startup configuration of 05-05. It is the main reason for the warning in §6.

# The command that isolates the requests and responses of the failing service:
grep -A30 "REQUEST POST-SIGN" trace.log | grep -B2 -A25 "rds.eu-west-1"

  1. The funnel: from 4,000 lines to 12

This is module 8's debt: "a 4,000-line log". The procedure is always the same, five steps, each one reducing things by an order of magnitude.

flowchart TD
    A["45,000 lines<br/>full TF_LOG=TRACE"] --> B["1. Narrow by LEVEL and ORIGIN<br/>TF_LOG_PROVIDER=TRACE<br/>TF_LOG_CORE=INFO"]
    B --> C["18,000 lines"]
    C --> D["2. Narrow by RESOURCE<br/>grep tf_resource_type"]
    D --> E["1,400 lines"]
    E --> F["3. Narrow by PHASE<br/>grep tf_rpc=ApplyResourceChange"]
    F --> G["260 lines"]
    G --> H["4. Isolate the OPERATION<br/>grep tf_req_id=&lt;id&gt;"]
    H --> I["45 lines"]
    I --> J["5. Extract the REQUEST<br/>and the RESPONSE<br/>that failed"]
    J --> K["12 lines<br/>that explain the failure"]

    style A fill:#fee2e2,stroke:#b91c1c
    style K fill:#dcfce7,stroke:#15803d

Let us walk through it with a real EcoMarket case: the prod apply fails while creating the ECS service, with an uninformative message, and the log has 41,800 lines.

Step 0: generate the right trace

mkdir -p /tmp/tf-debug && rm -f /tmp/tf-debug/*.log

# Provider at full volume; core only enough to find your bearings.
export TF_LOG_CORE=INFO
export TF_LOG_PROVIDER=TRACE
export TF_LOG_PATH=/tmp/tf-debug/apply.log

terraform apply plan.tfplan || true    # we want the trace even if it fails

wc -l /tmp/tf-debug/apply.log
18234 /tmp/tf-debug/apply.log

From 41,800 down to 18,234 just by choosing the variables well. Step 1 done.

Step 1b: get your bearings before filtering

Before searching for anything, two commands that give you the map:

# Which resources appear in the trace and how many lines does each take up?
grep -o 'tf_resource_type=[a-z0-9_]*' /tmp/tf-debug/apply.log \
  | sort | uniq -c | sort -rn | head -10
   4821 tf_resource_type=aws_ecs_service
   3102 tf_resource_type=aws_ecs_task_definition
   2044 tf_resource_type=aws_lb_target_group
   1877 tf_resource_type=aws_db_instance
    993 tf_resource_type=aws_security_group
# Where is the time going? Gaps of more than 5 seconds between lines.
awk '
  {
    # Pull the timestamp off the start of the line.
    if (match($0, /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.]+Z/)) {
      ts = substr($0, RSTART, RLENGTH)
      # Convert hh:mm:ss.mmm into seconds.
      split(substr(ts, 12, 12), t, ":")
      sec = t[1]*3600 + t[2]*60 + t[3]
      if (prev != "" && sec - prev > 5) {
        printf "%6.1fs gap before: %s\n", sec - prev, substr($0, 1, 130)
      }
      prev = sec
    }
  }
' /tmp/tf-debug/apply.log
  12.4s gap before: 2026-09-23T08:16:02.118Z [TRACE] provider...: Received request: tf_rpc=ApplyResourceChange tf_resource_type=aws_ecs_service
 187.3s gap before: 2026-09-23T08:19:09.455Z [ERROR] provider...: Response contains error diagnostic: tf_resource_type=aws_ecs_service

That is already half the diagnosis. There is a 187-second gap before the error, on aws_ecs_service. The provider spent three minutes waiting for something. It is not an immediate error; it is a retry or a stabilisation wait.

This little awk is, in my experience, the most profitable tool in the whole lesson for diagnosing hangs. Keep it in the repository as ci/gaps.awk.

Step 2: narrow by resource

grep "aws_ecs_service" /tmp/tf-debug/apply.log > /tmp/tf-debug/ecs.log
wc -l /tmp/tf-debug/ecs.log
4821 /tmp/tf-debug/ecs.log

Step 3: narrow by phase

# Which RPCs are there, and how many of each?
grep -o 'tf_rpc=[A-Za-z]*' /tmp/tf-debug/ecs.log | sort | uniq -c
     12 tf_rpc=ApplyResourceChange
      4 tf_rpc=PlanResourceChange
      2 tf_rpc=ReadResource
   4803 tf_rpc=ValidateResourceConfig

The 4,803 validation lines are pure noise. What matters are the 12 ApplyResourceChange ones:

grep "tf_rpc=ApplyResourceChange" /tmp/tf-debug/ecs.log

Step 4: isolate the operation by tf_req_id

# Extract the ID of the request that ended in an error.
ID=$(grep -m1 "ERROR" /tmp/tf-debug/ecs.log | grep -o 'tf_req_id=[a-f0-9-]*' | cut -d= -f2)
echo "Operation: ${ID}"

# And now EVERY line of that operation, in order, from the ORIGINAL log
# (not the filtered one, so we do not lose the lines without tf_resource_type).
grep "${ID}" /tmp/tf-debug/apply.log > /tmp/tf-debug/operation.log
wc -l /tmp/tf-debug/operation.log
Operation: 7d2e4f81-3a56-4b90-8c17-e5f0a92d6b48
45 /tmp/tf-debug/operation.log

From 41,800 lines to 45. And these 45 are a single complete operation: the request, the retries, the response and the error.

Step 5: extract what explains the failure

grep -A25 "REQUEST POST-SIGN\|RESPONSE" /tmp/tf-debug/operation.log | head -60
2026-09-23T08:16:02.204Z [DEBUG] provider.terraform-provider-aws_v5.62.0_x5: [DEBUG] AWS API Request Details
---[ REQUEST POST-SIGN ]-----------------------------
POST / HTTP/1.1
Host: ecs.eu-west-1.amazonaws.com
X-Amz-Target: AmazonEC2ContainerServiceV20141113.CreateService
{"cluster":"ecomarket-prod","serviceName":"ecomarket-prod-web","desiredCount":6,
 "taskDefinition":"ecomarket-prod-web:47","launchType":"FARGATE",
 "networkConfiguration":{"awsvpcConfiguration":{"subnets":["subnet-0a1b...","subnet-0c3d..."],
 "securityGroups":["sg-0e5f..."],"assignPublicIp":"DISABLED"}},
 "loadBalancers":[{"targetGroupArn":"arn:aws:elasticloadbalancing:eu-west-1:123456789014:targetgroup/ecomarket-prod-web/9a8b7c6d","containerName":"web","containerPort":8080}]}
-----------------------------------------------------
...
2026-09-23T08:19:09.455Z [DEBUG] provider.terraform-provider-aws_v5.62.0_x5: [DEBUG] AWS API Response Details
---[ RESPONSE ]--------------------------------------
HTTP/1.1 400 Bad Request
{"__type":"InvalidParameterException","message":"The target group with targetGroupArn
 arn:aws:elasticloadbalancing:eu-west-1:123456789014:targetgroup/ecomarket-prod-web/9a8b7c6d
 does not have an associated load balancer."}
-----------------------------------------------------

Twelve lines that explain the failure. The target group exists but is not attached to any load balancer, because the aws_lb_listener is created in parallel and ECS requires it beforehand. It is an ordering problem that depends_on fixes, and the original error message — "InvalidParameterException" — said so nowhere.

The funnel, boiled down to a script

#!/usr/bin/env bash
# ci/funnel.sh — reduces a Terraform trace to the failure that matters.
# Usage: ci/funnel.sh <file.log> [resource_type]
set -euo pipefail

LOG="$1"
RESOURCE="${2:-}"
OUTDIR="$(mktemp -d)"

echo "=== 1. Original size: $(wc -l < "$LOG") lines ==="

echo "=== 2. Resources present ==="
grep -o 'tf_resource_type=[a-z0-9_]*' "$LOG" | sort | uniq -c | sort -rn | head -10

echo "=== 3. Errors in the trace ==="
grep -c '\[ERROR\]' "$LOG" || echo "0"
grep '\[ERROR\]' "$LOG" | head -5 | cut -c1-160

echo "=== 4. Request IDs with an error ==="
IDS=$(grep '\[ERROR\]' "$LOG" | grep -o 'tf_req_id=[a-f0-9-]*' | cut -d= -f2 | sort -u)
echo "$IDS"

echo "=== 5. Complete operations ==="
for id in $IDS; do
  grep "$id" "$LOG" > "${OUTDIR}/${id}.log"
  echo "  ${OUTDIR}/${id}.log  ($(wc -l < "${OUTDIR}/${id}.log") lines)"
done

echo
echo "Look at the files above. To see request and response:"
echo "  grep -A25 'REQUEST POST-SIGN\\|RESPONSE' ${OUTDIR}/<id>.log"

  1. Trace hygiene: what to filter out before sharing

In 08-01 we decided that TF_LOG is left empty by default in EcoMarket's pipeline, "because debug logs include the API's request and response bodies". This section expands on that decision and its procedure.

6.1. What a trace really contains

Content Risk Does the provider censor it?
Account number, region, full ARNs Low-medium: reveals your topology and naming scheme No
The signed Authorization header Low: the signature expires in minutes and is not reusable No
X-Amz-Security-Token High: it is a temporary credential, valid for up to an hour No
Attribute values (names, CIDRs, sizes) Medium No
Passwords the provider marks as sensitive — Sometimes (REDACTED)
EC2 user_data, secret_string, template values High: this is where the startup configuration lives No
A container's environment variables High No
State contents during refresh operations High: the state contains everything No

The row that causes incidents is X-Amz-Security-Token. A trace from a recent apply pasted into a public issue contains temporary credentials that may still be valid when somebody reads it. At EcoMarket the policy is that any shared trace goes through the filter before it leaves the team, no exceptions.

6.2. The filter

#!/usr/bin/env bash
# ci/scrub-trace.sh — leaves a trace fit for sharing.
# Usage: ci/scrub-trace.sh trace.log > clean-trace.log
#
# CAUTION: this reduces the risk, it does NOT eliminate it. After running it
# you must READ the result before publishing it. A sensitive value in a field
# this script does not know about is still there.
set -euo pipefail

sed -E \
  -e 's/(X-Amz-Security-Token:).*/\1 <TOKEN-REMOVED>/I' \
  -e 's/(Authorization:).*/\1 <SIGNATURE-REMOVED>/I' \
  -e 's/(SessionToken=)[^&"[:space:]]*/\1<REMOVED>/g' \
  -e 's/(AccessKeyId=)[^&"[:space:]]*/\1<REMOVED>/g' \
  -e 's/(Password[A-Za-z]*=)[^&"[:space:]]*/\1<REMOVED>/gI' \
  -e 's/(UserData=)[^&"[:space:]]*/\1<REMOVED>/g' \
  -e 's/("secretString"[[:space:]]*:[[:space:]]*)"[^"]*"/\1"<REMOVED>"/gI' \
  -e 's/[0-9]{12}/123456789012/g' \
  -e 's/(ecomarket)-(dev|staging|prod)/\1-ENVIRONMENT/g' \
  "$1"

Line by line, what each rule neutralises:

  1. X-Amz-Security-Token — the temporary credential. It is the most urgent.
  2. Authorization — the signature. It is not reusable, but it reveals the AccessKeyId.
  3. SessionToken= / AccessKeyId= — the same credentials when they travel in the body instead of in headers.
  4. Password...= — any parameter whose name contains "password", case-insensitively.
  5. UserData= — the startup script, which at EcoMarket contains the application's configuration.
  6. secretString — the Secrets Manager body.
  7. [0-9]{12} — every twelve-digit number becomes the fictitious account. This replaces account numbers in ARNs, in messages and in identities, all in one go.
  8. ecomarket-<environment> — anonymises the environment.

And after the filter, you have to read the result. This is the part people skip and the part that matters:

ci/scrub-trace.sh /tmp/tf-debug/operation.log > /tmp/tf-debug/for-issue.log

# One last manual pass: look for what the filter does not know about.
grep -inE 'password|secret|token|key|credential|private|bearer' /tmp/tf-debug/for-issue.log

If that last search returns anything other than <REMOVED>, read it before you publish anything.

The rule that saves grief. Share the minimal fragment, not the file. After the funnel of §5 you have 12 lines that explain the failure. Those 12 lines, filtered and read, are what goes into the issue. The 18,000-line file adds nothing the 12 do not say, and it multiplies the exposure surface a thousandfold.

6.3. Why it is off in CI, and how to switch it on when you need it

The reasoning of 08-01 is twofold: the risk of a debug log ending up in a long-retention system, accessible to a lot of people; and the cost, because a TF_LOG=DEBUG on every run multiplies the size of CI's logs. EcoMarket's procedure for switching it on temporarily is in §14.

  1. terraform console as an expression debugger

06-02 introduced terraform console as a way of learning functions. Here it is used as what it also is: a debugger with full access to the state and the modules.

terraform console
> local.prefix
"ecomarket-prod"

What makes it useful for diagnosis is that it loads the state. It is not an expression calculator: it is a window onto what Terraform knows right now.

7.1. Checking a for_each before it fails

Use number one, and the one that prevents the unknown-values error of 09-01 §7:

> keys(var.environments)
[
  "dev",
  "prod",
  "staging",
]

> { for d in local.domains : d => length(d) }
{
  "api.ecomarket.example.com" = 25
  "ecomarket.example.com" = 21
  "www.ecomarket.example.com" = 25
}

Seeing the map before you write it into a for_each solves two classes of problem at once: duplicate keys (which produce Two different items produced the key ... in this 'for' expression) and unexpected keys.

> { for s in var.services : s.name => s }
╷
│ Error: Duplicate object key
│
│   on <console-input> line 1:
│   (source code not available)
│
│ Two different items produced the key "web" in this 'for' expression. If duplicates
│ are expected, use the ellipsis (...) after the value expression to enable grouping by
│ key.
╵

The same error you would have seen in the plan, but in a second and without locking the state.

7.2. Inspecting module.

The Unsupported attribute case of 09-01 §6.2 is settled here:

> keys(module.network)
[
  "private_subnets",
  "public_subnets",
  "vpc_id",
]

> module.network.private_subnets
[
  "subnet-0a1b2c3d4e5f67890",
  "subnet-0c3d4e5f6a7b89012",
  "subnet-0e5f6a7b8c9d01234",
]

> length(module.network.private_subnets)
3

Three queries and you know exactly what the module offers and what it evaluates to. Important: terraform console only sees the module's outputs, not its internal resources, because that is the real surface (which is precisely what the previous lesson explained).

7.3. Trying try and can on real data

> can(var.environments["production"])
false

> try(var.environments["production"].db_class, "DOES NOT EXIST")
"DOES NOT EXIST"

> try(var.environments["prod"].db_class, "DOES NOT EXIST")
"db.r6g.xlarge"

can() returns a boolean instead of failing, and it is the way to check hypotheses without the console aborting. It is especially useful for verifying the shape of nested data before writing a long expression:

> can(var.environments["prod"].scaling.rules[0].threshold)
false

A false there has just told you, in one second, that the structure you were about to write does not exist.

7.4. Getting at the resources' state

> aws_db_instance.main.endpoint
"ecomarket-prod-db-noble-bee.c9x8y7z6.eu-west-1.rds.amazonaws.com:5432"

> aws_db_instance.main.tags
{
  "Environment" = "prod"
  "ManagedBy" = "terraform"
  "Owner" = "[email protected]"
  "Project" = "EcoMarket"
  "Repo" = "ecomarket-infra"
}

This reads the state, not the cloud. It is the quick way to answer "what does Terraform think is there?", which is half the question in the drift diagnosis of 09-03.

7.5. The limitations you need to know about

Limitation Consequence Alternative
It does not evaluate unknown values A resource that has not been created gives (known after apply) The plan in JSON, §8
It does not see each, count.index, self You cannot test expressions from inside a block with for_each Extract the expression into a local and query that
It acquires the state lock An open session locks the remote state terraform console -state=copy.tfstate, or use -lock=false carefully
It needs init to have been run It is no use on an uninitialised directory —

The third deserves attention at EcoMarket: leaving a console open against prod while you go to lunch locks the state and another team's deployment fails with the error of 09-01 §12.1. Leave the console with exit or Ctrl-D.

  1. The plan in JSON: replace_paths and after_unknown

This is by some distance Terraform's most under-used tool. The human-readable plan hides information that is right there in the JSON.

terraform plan -out=plan.tfplan
terraform show -json plan.tfplan > plan.json

8.1. The structure

jq 'keys' plan.json
[
  "applyable",
  "checks",
  "complete",
  "configuration",
  "errored",
  "format_version",
  "planned_values",
  "prior_state",
  "relevant_attributes",
  "resource_changes",
  "timestamp",
  "variables"
]
Key Content What you will use it for
resource_changes One entry per resource with before, after, after_unknown, actions, replace_paths 90% of the diagnosis
planned_values The state as it would end up Checking the expected result
prior_state The state beforehand Comparing
configuration The parsed HCL, with expressions and references Seeing what references what
checks The results of the check blocks (06-05) Health
relevant_attributes Which attributes of other resources influence this plan Understanding dependencies
variables The resolved input values Confirming which .tfvars won

variables deserves a mention of its own, because it answers a very frequent question: "which value is it actually using?". With common.auto.tfvars and environments/<environment>.tfvars layered on top of each other, the order of precedence is not always obvious:

jq -r '.variables | to_entries[] | "\(.key) = \(.value.value | tostring)"' plan.json \
  | grep -v password
environment = "prod"
environments = {"dev":{...},"prod":{"db_class":"db.r6g.xlarge",...},"staging":{...}}
project = "ecomarket"
region = "eu-west-1"

One line and the argument about which .tfvars was applied is over. (The grep -v password is not decorative: var.db_password is sensitive, but its value does appear in this JSON. See §8.5.)

8.2. replace_paths: why a resource is being replaced

The most expensive case: the plan says must be replaced on the production database and the text output marks one attribute with # forces replacement, but when twenty attributes have changed it is easy to lose sight of it. The JSON says it unambiguously:

jq -r '.resource_changes[]
       | select(.change.actions == ["delete","create"] or .change.actions == ["create","delete"])
       | {
           resource: .address,
           action: (.change.actions | join(" then ")),
           forces_replacement: .change.replace_paths
         }' plan.json
{
  "resource": "aws_db_instance.main",
  "action": "create then delete",
  "forces_replacement": [["engine_version"]]
}
{
  "resource": "aws_launch_template.app",
  "action": "delete then create",
  "forces_replacement": [["network_interfaces", 0, "subnet_id"]]
}

This is the exact answer. Not "something changed": engine_version in the first, and network_interfaces[0].subnet_id in the second. The nested path in the second case is information the text plan presents far less clearly.

And create then delete versus delete then create is not a detail: the first is create_before_destroy (the new resource exists before the old one is deleted, with no outage) and the second is not (there is a window with no service). For prod, that difference is the incident.

# And the specific value that changes, which is the next thing you will want to see:
jq -r '.resource_changes[]
       | select(.address == "aws_db_instance.main")
       | {before: .change.before.engine_version, after: .change.after.engine_version}' plan.json
{
  "before": "16.3",
  "after": "16.9"
}

8.3. after_unknown: what is unknown and who makes it unknown

This is the method 09-01 §7 promised. When Terraform says a for_each depends on unknown values, here is the proof.

after_unknown is an object with the same shape as after, where every leaf is true (unknown) or false:

jq -r '.resource_changes[]
       | select(.address == "aws_acm_certificate.main")
       | .change.after_unknown' plan.json
{
  "arn": true,
  "domain_validation_options": true,
  "id": true,
  "not_after": true,
  "not_before": true,
  "status": true,
  "tags_all": false,
  "validation_emails": true
}

domain_validation_options: true is exactly the confirmation you needed: that attribute will not exist until apply, and that is why it cannot feed a for_each.

The complete listing of everything unknown in a plan, which is what you will use when you do not even know where to start:

jq -r '.resource_changes[]
       | . as $r
       | (.change.after_unknown // {})
       | paths(. == true) as $p
       | "\($r.address).\($p | join("."))"' plan.json \
  | sort | head -30

What it does, step by step:

  1. . as $r stores the whole resource so its address can be used later.
  2. .change.after_unknown // {} takes the unknowns object (or an empty one if there is none).
  3. paths(. == true) is the key jq part: it returns the path of every leaf whose value is true, as an array of components.
  4. "\\($r.address).\\($p | join("."))" joins the address and the path into one readable line.
aws_acm_certificate.main.arn
aws_acm_certificate.main.domain_validation_options
aws_db_instance.main.address
aws_db_instance.main.endpoint
aws_lb.main.dns_name
aws_lb.main.zone_id

And to find out who makes it unknown, configuration holds the references:

jq -r '.configuration.root_module.resources[]
       | select(.address == "aws_route53_record.validation")
       | .expressions' plan.json
{
  "for_each": {
    "references": [
      "aws_acm_certificate.main.domain_validation_options",
      "aws_acm_certificate.main"
    ]
  },
  "zone_id": {
    "references": ["data.aws_route53_zone.main.zone_id",
                   "data.aws_route53_zone.main"]
  }
}

Diagnosis closed in two commands: the for_each references aws_acm_certificate.main.domain_validation_options, and that attribute is marked unknown. Cause and proof, without reading a single line of trace.

8.4. Differences between before and after

# Which attributes change on a resource, without the noise of the ones that do not.
jq -r '.resource_changes[]
       | select(.address == "aws_ecs_task_definition.web")
       | .change as $c
       | ($c.before // {}) as $b
       | ($c.after // {}) as $a
       | ($b + $a | keys[]) as $k
       | select(($b[$k] | tostring) != ($a[$k] | tostring))
       | "\($k):\n  before: \($b[$k] | tostring | .[0:100])\n  after:  \($a[$k] | tostring | .[0:100])"' plan.json
container_definitions:
  before: [{"cpu":512,"environment":[{"name":"LOG_LEVEL","value":"info"}],"image":"123456789
  after:  [{"cpu":1024,"environment":[{"name":"LOG_LEVEL","value":"debug"}],"image":"1234567
revision:
  before: 47
  after:  null

This query is the one that saves you when a resource with a huge JSON attribute — an ECS task definition, an IAM policy — changes and the text diff is unreadable. Truncating to 100 characters avoids dumping three screenfuls; drop it once you have identified the attribute.

8.5. The security warning about the plan in JSON

Warning. terraform show -json plan.tfplan reveals sensitive values in the clear. The plan.tfplan file already contained them — that is what 08-01 warned about regarding the plan artefact — and the JSON exposes them without the (sensitive value) markers of the text output. var.db_password is right there, readable, in .variables.db_password.value.

Practical consequences for EcoMarket:

# WRONG: publishing the complete JSON as a PR artefact.
terraform show -json plan.tfplan > plan-public.json

# RIGHT: extract only what the reviewer needs.
jq '{
      summary: [.resource_changes[] | select(.change.actions != ["no-op"])
                | {addr: .address, actions: .change.actions,
                   replaces: (.change.replace_paths // [])}],
      checks: .checks
    }' plan.tfplan.json > public-summary.json

The complete JSON stays on the runner and is destroyed with it; the summary is what gets published. It is the same discipline as the trace filter of §6.

  1. terraform plan -json: the output for machines

Different from show -json, and people confuse the two:

terraform show -json plan.tfplan terraform plan -json
What it produces One JSON object with the complete plan A stream of JSON lines, one per event
When After planning During planning
What for Analysing the result Following progress, capturing diagnostics, integrating with a UI
Contains The whole plan Events: start, per-resource progress, diagnostics, summary
terraform plan -json -out=plan.tfplan 2>/dev/null | head -5
{"@level":"info","@message":"Terraform 1.9.5","@module":"terraform.ui","@timestamp":"2026-09-23T08:14:22.481Z","terraform":"1.9.5","type":"version","ui":"1.2"}
{"@level":"info","@message":"aws_db_instance.main: Refreshing state... [id=ecomarket-prod-db-noble-bee]","@module":"terraform.ui","hook":{"id_key":"id","id_value":"ecomarket-prod-db-noble-bee","resource":{"addr":"aws_db_instance.main","resource_type":"aws_db_instance"}},"type":"refresh_start"}
{"@level":"info","@message":"aws_lb.main: Plan to update","@module":"terraform.ui","change":{"action":"update","resource":{"addr":"aws_lb.main"}},"type":"planned_change"}
{"@level":"warn","@message":"Warning: Argument is deprecated","@module":"terraform.ui","diagnostic":{"severity":"warning","summary":"Argument is deprecated","detail":"Use the aws_s3_bucket_acl resource instead","range":{"filename":"infra/data/datastore.tf","start":{"line":12,"column":3}}},"type":"diagnostic"}
{"@level":"info","@message":"Plan: 0 to add, 2 to change, 0 to destroy.","@module":"terraform.ui","changes":{"add":0,"change":2,"remove":0,"operation":"plan"},"type":"change_summary"}

The event types that matter:

type When it is emitted Use in diagnosis
version At the start Confirming the version without a separate command
refresh_start / refresh_complete For every refreshed resource Seeing where the refresh gets stuck
planned_change For every planned change Counting changes live
diagnostic Errors and warnings Capturing every warning, with its range (file and line)
change_summary At the end The numeric summary for the pipeline gate
apply_start / apply_progress / apply_complete During apply apply_progress emits the elapsed time: where an apply hangs
# The most valuable diagnostic use: seeing which resource is taking its time
# during an apply that looks hung.
terraform apply -json plan.tfplan \
  | jq -r 'select(.type == "apply_progress")
           | "\(.hook.elapsed_seconds)s  \(.hook.resource.addr)"'
10s  aws_db_instance.main
20s  aws_db_instance.main
...
590s  aws_db_instance.main
600s  aws_db_instance.main

Ten minutes on the database and no other resource making progress. That is not a hang: it is RDS building a Multi-AZ instance. Knowing that stops you cancelling the job, which is what produces the orphaned locks of 09-03.

And the warning capture for the pipeline, which closes the matter from 09-01 §1:

terraform plan -json -out=plan.tfplan \
  | tee >(jq -r 'select(.type=="diagnostic")
                 | "[\(.diagnostic.severity)] \(.diagnostic.summary) — \(.diagnostic.range.filename // "-"):\(.diagnostic.range.start.line // 0)"' \
          > diagnostics.txt) \
  | jq -r 'select(.type=="change_summary") | .["@message"]'

tee >(...) duplicates the stream: one copy goes to the diagnostics extractor and the other carries on to the summary. Both files are published as job artefacts.

  1. terraform graph and reading a cycle

terraform graph
digraph {
	compound = "true"
	newrank = "true"
	subgraph "root" {
		"[root] aws_security_group.app (expand)" -> "[root] module.network.aws_vpc.main (expand)"
		"[root] aws_security_group.db (expand)" -> "[root] aws_security_group.app (expand)"
		"[root] aws_security_group.app (expand)" -> "[root] aws_security_group.db (expand)"
		"[root] aws_db_instance.main (expand)" -> "[root] aws_security_group.db (expand)"
	}
}

It reads as "A depends on B": "A" -> "B" means A needs B to exist first. The cycle in the example jumps out in the two middle lines: db -> app and app -> db.

10.1. With Graphviz

# Install: apt install graphviz / brew install graphviz
terraform graph | dot -Tsvg > graph.svg

For EcoMarket's complete prod state the SVG is unreadable: hundreds of nodes. The real use is to filter before drawing:

# Only the nodes that appear in the Cycle message.
terraform graph \
  | grep -E 'digraph|^\}|subgraph|security_group|aws_db_instance' \
  | dot -Tsvg > cycle.svg
# Or, without Graphviz, in text: what depends on what, for one resource only.
terraform graph | grep '"\[root\] aws_security_group.db' | sed 's/^\s*//'
"[root] aws_security_group.db (expand)" -> "[root] aws_security_group.app (expand)"
"[root] aws_security_group.db (expand)" -> "[root] module.network.aws_vpc.main (expand)"
"[root] aws_db_instance.main (expand)" -> "[root] aws_security_group.db (expand)"

Three lines that say: db needs app and the VPC; and main needs db. Combined with the symmetric grep on app, the cycle is documented.

10.2. The graph types

terraform graph -type=plan        # the plan graph (the default)
terraform graph -type=apply       # the apply graph
terraform graph -type=plan-destroy

The detail that matters: the apply graph includes nodes for the resources that are going to be created, and the plan one does not always. If a cycle appears only in apply, you have to ask for that graph explicitly. And terraform graph requires neither credentials nor a valid state: it works on the configuration, so it is useful even when the plan is failing.

10.3. An alternative that is often better

For understanding dependencies in a specific case, relevant_attributes from the plan JSON is more direct than the graph:

jq -r '.relevant_attributes[]
       | "\(.resource).\(.attribute | join("."))"' plan.json | sort -u | head -20

It returns which attributes of which resources influence this plan. It is a very small subset of the graph and it is usually exactly what you are after.

  1. Probes: temporary outputs and terraform_data

When an expression is too complex for terraform console — because it uses each, count.index or self — you have to instrument the configuration.

11.1. Temporary outputs

# TEMPORARY DEBUGGING — delete before merging. Ticket INFRA-4821.
output "debug_subnets" {
  value = {
    from_module = module.network.private_subnets
    how_many    = length(module.network.private_subnets)
    by_az       = { for s in data.aws_subnet.private : s.availability_zone => s.id }
    data_type   = can(tomap(module.network.private_subnets)) ? "map" : "list"
  }
}
# Without applying anything: the plan already computes the outputs.
terraform plan -out=plan.tfplan >/dev/null
terraform show -json plan.tfplan | jq '.planned_values.outputs.debug_subnets.value'

The advantage over console: the output is evaluated in the plan's full context, with everything resolved. The disadvantage: you have to remember to delete it.

Warning. A temporary output that reaches main is a real problem, not untidiness. Outputs are stored in the state and are readable by anyone with access to the bucket. If your probe printed the database password "just for a moment", that password is now in the production state, without sensitive = true, and it will stay there after you delete the output — until the next apply. EcoMarket's convention: every debugging output carries the debug_ prefix, and CI fails if it finds one.

# ci/no-probes.sh — a mandatory check in the pipeline.
if grep -rn 'output "debug_\|resource "terraform_data" "debug_' \
     --include='*.tf' infra/ modules/ ; then
  echo "ERROR: there are debugging probes in the code. Delete them before merging."
  exit 1
fi

11.2. terraform_data as a probe

terraform_data is a resource with no side effects that stores whatever you give it. It works as a probe that is recorded in the state and shows up in the plan:

# TEMPORARY DEBUGGING — INFRA-4821.
resource "terraform_data" "debug_for_each" {
  input = {
    keys     = keys(local.computed_services)
    how_many = length(local.computed_services)
    first    = try(values(local.computed_services)[0], null)
    taken_at = timestamp()
  }
}

The plan shows it like this:

  # terraform_data.debug_for_each will be created
  + resource "terraform_data" "debug_for_each" {
      + id     = (known after apply)
      + input  = {
          + first    = {
              + cpu  = 512
              + port = 8080
            }
          + how_many = 3
          + keys     = [
              + "api",
              + "web",
              + "worker",
            ]
        }
    }

When to use which:

Probe Advantage Drawback
A temporary output Creates nothing; visible with terraform output Stored in the state with no sensitivity markers
terraform_data Shows the complete structure in the plan, formatted Creates an entry in the state you have to remove (state rm or delete the block)
A check with an interpolating error_message (06-05) Creates nothing, and can stay permanently Only emits if the condition fails

The third option is the most elegant for recurring diagnostics, and it is the one EcoMarket uses in guards.tf:

# This one is not temporary: it stays. If the number of subnets stops being 3,
# the plan says so with the real value, instead of failing ten lines further down
# with an "Invalid index".
check "expected_subnets" {
  assert {
    condition = length(module.network.private_subnets) == 3
    error_message = format(
      "3 private subnets were expected and there are %d: %s",
      length(module.network.private_subnets),
      join(", ", module.network.private_subnets)
    )
  }
}

  1. terraform providers and providers schema -json

Two commands that, between them, settle the entire Unsupported argument / Unsupported attribute family caused by version mismatches in 09-01 §5.1 and §6.2.

12.1. terraform providers

terraform providers
Providers required by configuration:
.
├── provider[registry.terraform.io/hashicorp/aws] ~> 5.60
├── provider[registry.terraform.io/hashicorp/random]
├── module.platform
│   ├── provider[registry.terraform.io/hashicorp/aws] >= 5.30.0
│   └── module.data
│       └── provider[registry.terraform.io/hashicorp/aws] >= 5.30.0
└── module.network
    └── provider[registry.terraform.io/hashicorp/aws] >= 5.0.0

Providers required by state:

    provider[registry.terraform.io/hashicorp/aws]
    provider[registry.terraform.io/hashicorp/random]

Two sections, and both matter:

  • "required by configuration" is the constraint tree: who asks for what. It is what settles the empty-intersection error.
  • "required by state" is which providers appear in the state. If there is one here that is no longer in the configuration, you have resources orphaned from a provider you no longer use, and the next init will complain.
# The EXACT version that is installed, not the constraint:
terraform version
Terraform v1.9.5
on linux_amd64
+ provider registry.terraform.io/hashicorp/aws v5.62.0
+ provider registry.terraform.io/hashicorp/random v3.6.2

12.2. terraform providers schema -json

The complete schema of everything the installed provider knows how to do. It is an enormous JSON — of the order of 100 MB for the AWS provider — so it is always queried with jq:

terraform providers schema -json > /tmp/schema.json
ls -lh /tmp/schema.json
-rw-r--r-- 1 joan joan 118M sep 23 08:31 /tmp/schema.json

Query 1: does this argument exist in my version?

jq -r '.provider_schemas["registry.terraform.io/hashicorp/aws"]
       .resource_schemas["aws_db_instance"].block.attributes
       | keys[]' /tmp/schema.json | grep -i master
master_user_secret_kms_key_id
master_username

manage_master_user_password is not there. Diagnosis closed: it is not a typo, it is that your provider version does not have it. The fix is to raise the provider, not to correct the line.

Query 2: which attributes does this resource return? Useful when an output fails with Unsupported attribute:

jq -r '.provider_schemas["registry.terraform.io/hashicorp/aws"]
       .resource_schemas["aws_db_instance"].block.attributes
       | to_entries[]
       | select(.value.computed == true and (.value.optional // false) == false)
       | .key' /tmp/schema.json | head -20

This lists the read-only attributes — the ones that exist after creation — which are exactly the ones used in outputs.

Query 3: which nested blocks does it accept? The diagnosis for Unsupported block type:

jq -r '.provider_schemas["registry.terraform.io/hashicorp/aws"]
       .resource_schemas["aws_s3_bucket"].block.block_types
       | keys[]' /tmp/schema.json
timeouts

Only timeouts. It confirms that lifecycle_rule, versioning and company are no longer blocks of aws_s3_bucket in this version.

Query 4: which arguments are required?

jq -r '.provider_schemas["registry.terraform.io/hashicorp/aws"]
       .resource_schemas["aws_ecs_service"].block.attributes
       | to_entries[]
       | select(.value.required == true)
       | "\(.key)  (\(.value.type | tostring))"' /tmp/schema.json

Query 5: which attributes does the provider mark as sensitive? Relevant to §6 and to 07-04:

jq -r '.provider_schemas["registry.terraform.io/hashicorp/aws"]
       .resource_schemas | to_entries[]
       | .key as $r | .value.block.attributes // {} | to_entries[]
       | select(.value.sensitive == true)
       | "\($r).\(.key)"' /tmp/schema.json | head -20

That list is exactly the set of attributes the provider will censor in the traces. Everything else goes through in the clear.

Tip. Generate schema.json once per provider version and keep it in /tmp. Regenerating it takes nearly a minute for the AWS provider, and during a diagnostic session you will query it ten times.

  1. Debugging nested modules

A debt from 04-01, 04-03 and 07-05. 09-01 §11 explained how to read the error's path; here is the procedure for working inside the module.

13.1. Locating the real code

# The complete map: logical address → physical path → exact origin.
jq -r '.Modules[] | select(.Key != "")
       | "\(.Key)\n    origin: \(.Source)\n    at:     \(.Dir)\n"' \
  .terraform/modules/modules.json
platform
    origin: git::ssh://[email protected]/ecomarket/terraform-aws-ecomarket-platform.git?ref=v3.4.0
    at:     .terraform/modules/platform

platform.data
    origin: ./modules/data
    at:     .terraform/modules/platform/modules/data

platform.network
    origin: ./modules/network
    at:     .terraform/modules/platform/modules/network

The Key → Terraform address translation: platform.data is module.platform.module.data. With that you can query it:

terraform state list | grep "^module.platform.module.data"
module.platform.module.data.aws_db_instance.main
module.platform.module.data.aws_db_parameter_group.main
module.platform.module.data.aws_db_subnet_group.main

13.2. Seeing the values that go into the module

A module's inputs are not directly visible in terraform console. The plan JSON does have them:

jq -r '.configuration.root_module.module_calls.platform.expressions
       | to_entries[]
       | "\(.key) = \(.value.constant_value // (.value.references | join(" + ")))"' plan.json
environment = "prod"
tags = local.common_tags
db_class = local.current.db_class
prefix = local.prefix
backup_retention = local.current.retention_days

And the resolved values, in planned_values:

jq -r '.planned_values.root_module.child_modules[]
       | select(.address == "module.platform")
       | .resources[] | {addr: .address, values: .values | keys}' plan.json | head -20

13.3. Isolating the module in a minimal directory

This is the technique that turns "the module fails" into "I have a reproduction". And it is also what gets an issue fixed (09-04).

mkdir -p /tmp/isolate-data && cd /tmp/isolate-data
# /tmp/isolate-data/main.tf
# Minimal reproduction of the module.platform.module.data failure.
# No remote backend, none of the rest of the infrastructure, no Terragrunt.

terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = {
      source = "hashicorp/aws"
      # The SAME version as in the environment where it fails. This is essential:
      # if you use a different one here, you are not reproducing anything.
      version = "= 5.62.0"
    }
  }
  # No backend block: local state, no locks, no risk.
}

provider "aws" {
  region = "eu-west-1"
}

module "data" {
  # Pointing at the DOWNLOADED copy is the right thing to do to reproduce the
  # exact failure: it is the code that is actually running.
  source = "/home/joan/ecomarket-infra/infra/app/.terraform/modules/platform/modules/data"

  # Every input with LITERAL values. No locals, no var.environments,
  # no references to other modules. If the failure survives this
  # simplification, it belongs to the module.
  prefix           = "ecomarket-test"
  db_class         = "db.t4g.micro"
  storage          = 20
  backup_retention = 1
  multi_az         = false
  subnets          = ["subnet-0a1b2c3d4e5f67890", "subnet-0c3d4e5f6a7b89012"]
  tags = {
    Project     = "EcoMarket"
    Environment = "test"
    ManagedBy   = "terraform"
    Owner       = "[email protected]"
    Repo        = "ecomarket-infra"
  }
}
terraform init
terraform plan

Three outcomes and three conclusions:

Outcome Conclusion Next step
Fails the same way The problem belongs to the module or the provider, and does not depend on your context Reduce further (§13.4) and report it (09-04)
Does not fail The problem is in how you call the module: a value, an aliased provider, a different version Add context back until it fails
Fails differently You changed something relevant without meaning to Check the provider and Terraform versions

13.4. Bisection

When the reproduction is still large, bisection cuts it down in logarithmic steps.

flowchart TD
    A["Configuration that fails<br/>(N blocks)"] --> B["Comment out HALF"]
    B --> C{"Does it still fail?"}
    C -->|Yes| D["The cause is in<br/>the half that REMAINS"]
    C -->|No| E["The cause is in<br/>the half I REMOVED"]
    D --> F["Repeat on<br/>that half"]
    E --> G["Restore that half,<br/>remove the other"]
    G --> F
    F --> H{"Is 1 block left?"}
    H -->|No| B
    H -->|Yes| I["Cause isolated"]

    style I fill:#dcfce7,stroke:#15803d

The discipline that makes it work, and that people skip:

  1. One change per iteration. If you remove two things and it stops failing, you do not know which it was.
  2. Use Git, even in a temporary directory. git init && git add -A && git commit before you start, and git stash to go back without thinking.
  3. Write down the result of every iteration. Three iterations later you will not remember which one failed.
# Bisection log — two lines per iteration, and it saves confusion.
cd /tmp/isolate-data && git init -q && git add -A && git commit -qm "baseline: fails"

echo "iter 1: without parameter_group          -> FAILS"     >> bisection.txt
echo "iter 2: without parameter_group or tags  -> DOES NOT FAIL"  >> bisection.txt
echo "  => the cause is in 'tags'"                            >> bisection.txt

For modules with examples/ — the convention of 04-02 — the work is already done: examples/complete/ is a minimal reproduction maintained by the author. Start there:

cd .terraform/modules/platform/examples/complete
terraform init && terraform plan

If the module's own official example fails with your provider version, you have a reportable issue in two minutes without writing a line of HCL.

  1. Debugging in CI: reproducing the runner

The closing of module 8 described the painful cycle: "edit, push, wait, read", fifteen minutes per attempt. The way to break it is to bring the runner onto your laptop.

14.1. Reproducing the environment

#!/usr/bin/env bash
# ci/reproduce-runner.sh — opens a shell identical to the pipeline's.
# Usage: ci/reproduce-runner.sh <environment>
set -euo pipefail

ENVIRONMENT="${1:?Usage: $0 <dev|staging|prod>}"

# 1. The SAME image as the runner. The version comes from the workflow itself,
#    so the two cannot diverge.
TF_VERSION=$(grep -oP 'terraform_version:\s*"\K[0-9.]+' \
             .github/workflows/terraform.yml | head -1)

# 2. The SAME role. None of your personal profile.
ACCOUNT=$(jq -r ".${ENVIRONMENT}" ci/accounts.json)
CREDS=$(aws sts assume-role \
  --role-arn "arn:aws:iam::${ACCOUNT}:role/ecomarket-terraform-plan-${ENVIRONMENT}" \
  --role-session-name "local-reproduction-$(whoami)" \
  --duration-seconds 3600 \
  --query 'Credentials' --output json)

docker run --rm -it \
  -v "$PWD:/work" -w /work \
  -e AWS_ACCESS_KEY_ID="$(jq -r .AccessKeyId <<<"$CREDS")" \
  -e AWS_SECRET_ACCESS_KEY="$(jq -r .SecretAccessKey <<<"$CREDS")" \
  -e AWS_SESSION_TOKEN="$(jq -r .SessionToken <<<"$CREDS")" \
  -e AWS_REGION="eu-west-1" \
  -e TF_IN_AUTOMATION=1 \
  -e TF_INPUT=false \
  -e ENVIRONMENT="${ENVIRONMENT}" \
  --entrypoint /bin/sh \
  "hashicorp/terraform:${TF_VERSION}" \
  -c 'terraform version && exec sh'

What each part replicates and why:

Element Which difference from the runner it eliminates
docker run hashicorp/terraform:<version> Terraform version and platform (linux_amd64)
assume-role with the plan role Credentials: the read-only role, not your administrator profile
A clean container Cold provider cache, no ~/.gitconfig, none of your .bashrc variables
TF_IN_AUTOMATION / TF_INPUT=false Non-interactive mode
No TTY from your shell (sh inside) Colourless behaviour

With this, the diagnostic cycle goes from fifteen minutes to fifteen seconds, which is the whole point of this section.

14.2. Switching TF_LOG on in the pipeline, under control

EcoMarket's policy: TF_LOG off by default, switchable on by hand, per run, with short retention and without publishing the trace as an open artefact.

# Fragment of .github/workflows/terraform.yml
on:
  workflow_dispatch:
    inputs:
      environment:
        type: choice
        options: [dev, staging, prod]
      debug:
        description: 'Enable TF_LOG=DEBUG (the trace is kept for 1 day, with restricted access)'
        type: boolean
        default: false

jobs:
  plan:
    runs-on: ubuntu-latest
    env:
      # Empty unless it is explicitly requested for this run.
      TF_LOG: ${{ inputs.debug && 'DEBUG' || '' }}
      TF_LOG_PATH: ${{ inputs.debug && 'trace/terraform.log' || '' }}
    steps:
      - uses: actions/checkout@v4

      - name: Prepare the trace directory
        if: inputs.debug
        run: mkdir -p trace

      # ... init and plan ...

      - name: Scrub the trace before uploading it
        if: inputs.debug && always()
        run: |
          ci/scrub-trace.sh trace/terraform.log > trace/terraform-scrubbed.log
          rm -f trace/terraform.log     # the original does NOT leave the runner
          # And a visible notice in the job summary.
          {
            echo "### Debug trace generated"
            echo ""
            echo "- Lines: \`$(wc -l < trace/terraform-scrubbed.log)\`"
            echo "- **The trace is scrubbed but NOT audited.** Review it before"
            echo "  sharing it outside the team. See module 9, lesson 2, §6."
          } >> "$GITHUB_STEP_SUMMARY"

      - name: Publish the scrubbed trace
        if: inputs.debug && always()
        uses: actions/upload-artifact@v4
        with:
          name: trace-${{ inputs.environment }}-${{ github.run_id }}
          path: trace/terraform-scrubbed.log
          retention-days: 1       # MINIMUM retention, deliberately

Four design decisions worth explaining:

  1. workflow_dispatch with a checkbox, not a repository variable. Switching debugging on is a conscious act, per run, and it records who launched it.
  2. The original never leaves the runner. It is scrubbed and deleted in the same step, before anything is uploaded.
  3. retention-days: 1. A trace has value during the diagnostic session. After that it is just accumulated risk.
  4. The notice in the job summary. Whoever downloads the artefact reads that it is scrubbed but not audited. The filter reduces the risk, it does not eliminate it (§6.2).

14.3. Diagnostic artefacts that are always worth publishing

These carry no secrets and cost seconds:

      - name: Diagnostic artefacts
        if: always()
        run: |
          mkdir -p diagnostics
          terraform version -json                 > diagnostics/version.json
          terraform providers                     > diagnostics/providers.txt
          cp .terraform.lock.hcl                    diagnostics/ || true
          cp .terraform/modules/modules.json        diagnostics/ || true
          date -u +%Y-%m-%dT%H:%M:%SZ             > diagnostics/clock.txt
          aws sts get-caller-identity \
            --query '{account:Account,arn:Arn}'    > diagnostics/identity.json
          env | grep -E '^(TF_|AWS_)' | sed 's/=.*/=<present>/' | sort \
                                                  > diagnostics/environment.txt

Version, providers, lock file, downloaded modules with their exact version, clock, identity and the variables present. They are the seven answers the method of 09-01 §4 asks for, available without running anything again.

  1. crash.log: when Terraform itself blows up

Sometimes the thing that fails is neither the provider nor your code: it is Terraform.

Stack trace from the terraform-provider-aws_v5.62.0_x5 plugin:

panic: interface conversion: interface {} is nil, not map[string]interface {}

goroutine 187 [running]:
github.com/hashicorp/terraform-provider-aws/internal/service/ecs.expandCapacityProviderStrategy(...)
	/home/runner/work/terraform-provider-aws/internal/service/ecs/service.go:1842
github.com/hashicorp/terraform-provider-aws/internal/service/ecs.resourceServiceUpdate(0xc0009a2000, ...)
	/home/runner/work/terraform-provider-aws/internal/service/ecs/service.go:1204
...

Error: The terraform-provider-aws_v5.62.0_x5 plugin crashed!

This is always indicative of a bug within the plugin. It would be immensely
helpful if you could report the crash with the plugin's maintainers so that it
can be fixed. The output above should help diagnose the issue.

How to read it, and it is easier than it looks:

Line What it tells you
Stack trace from the terraform-provider-aws_v5.62.0_x5 plugin The provider, not core. And its exact version
panic: interface conversion: interface {} is nil A nil value where a map was expected: an optional field with no value
ecs.expandCapacityProviderStrategy The exact function. Search for it in the provider's repository: there is almost always an issue
service.go:1842 The file and line of the provider's source code
resourceServiceUpdate The operation: it is an update, not a create

With expandCapacityProviderStrategy as your search term in hashicorp/terraform-provider-aws's issues, the odds of finding the exact issue are high. It is the best case of 09-04: a unique, searchable term.

What to do, in order:

  1. Locate the crash.log. Terraform writes it in the current directory. If it is not there, rerun with TF_LOG=TRACE and you will capture the same and more.
  2. Search for the panic's function in the provider's issues.
  3. Reduce. The isolation of §13.3 applied to the resource that produces the panic.
  4. A workaround in the meantime: drop down to the previous provider version, or remove the attribute involved (capacity_provider_strategy in the example) if it is dispensable.
  5. Report it with the reproduction and the scrubbed crash.log.

Warning. crash.log contains a full TRACE trace from before the panic. It is one of the most sensitive files Terraform produces: put it through the filter of §6 always before attaching it to a public issue.

If the thing that blows up is core — a panic without the Stack trace from the ... plugin line — the issue goes to hashicorp/terraform, and it is a very infrequent situation that almost always involves a corrupt state (09-03) or a development build.

  1. Debugging Terragrunt

Terragrunt adds a generation layer and an orchestration layer, and each has its own way of failing. The key is knowing which layer you are in.

flowchart TD
    A["A failure with Terragrunt"] --> B{"Does the message come<br/>from Terragrunt<br/>or from Terraform?"}
    B -->|"'ERRO[0001] ...'<br/>or an HCL error in terragrunt.hcl"| C["Terragrunt layer"]
    B -->|"Terraform's ╷│╵ box"| D{"Does the path contain<br/>.terragrunt-cache?"}

    C --> E["--terragrunt-log-level debug<br/>render-json"]
    D -->|Yes| F["Module code:<br/>the failure is Terraform's,<br/>but the INPUTS come from<br/>your terragrunt.hcl"]
    D -->|No| G["A pure Terraform failure"]

    F --> H["render-json:<br/>which inputs arrive?"]
    H --> I{"Are the inputs<br/>correct?"}
    I -->|No| J["The problem is in an<br/>include or a local:<br/>Terragrunt layer"]
    I -->|Yes| K["cd .terragrunt-cache/*/*/<br/>terraform plan<br/>→ pure Terraform"]

    style C fill:#fef3c7,stroke:#b45309
    style G fill:#dbeafe,stroke:#1d4ed8
    style K fill:#dbeafe,stroke:#1d4ed8

16.1. The commands

# 1. See what Terragrunt is doing: which files it generates, which command it runs.
terragrunt plan --terragrunt-log-level debug 2>&1 | head -40
DEBU[0000] Terragrunt Version: 0.67.4
DEBU[0000] Reading Terragrunt config file at live/prod/data/terragrunt.hcl
DEBU[0000] Included config live/prod/environment.hcl
DEBU[0000] Included config live/terragrunt.hcl
DEBU[0000] Downloading Terraform configurations from git::ssh://[email protected]/ecomarket/terraform-aws-ecomarket-platform.git?ref=v3.4.0 into .terragrunt-cache/xK9mP2nQ8vR4/tY7wL1zB3cF6
DEBU[0001] Generated file .terragrunt-cache/xK9mP2nQ8vR4/tY7wL1zB3cF6/backend.tf
DEBU[0001] Generated file .terragrunt-cache/xK9mP2nQ8vR4/tY7wL1zB3cF6/provider.tf
DEBU[0001] Running command: terraform init -backend-config=...

The Included config lines are gold: they say exactly which files make up the effective configuration, and in what order. Half an hour of "where does this value come from?" is settled here.

# 2. The REAL inputs after resolving every include, local and dependency.
terragrunt render-json --terragrunt-json-out /tmp/resolved.json
jq '.inputs' /tmp/resolved.json
{
  "prefix": "ecomarket-prod",
  "db_class": "db.r6g.xlarge",
  "backup_retention": "30",
  "multi_az": true,
  "tags": {
    "Environment": "prod",
    "ManagedBy": "terraform",
    "Owner": "[email protected]",
    "Project": "EcoMarket",
    "Repo": "ecomarket-infra"
  }
}

"backup_retention": "30" with quotes. There is the Invalid value for input variable of 09-01 §11.3, visible in one command.

# 3. Which files has Terragrunt GENERATED? They are the ones you did not write
#    and the ones that produce errors on lines you do not recognise.
find . -path '*/.terragrunt-cache/*' -name '*.tf' -newer terragrunt.hcl \
  -exec sh -c 'echo "=== $1 ==="; cat "$1"' _ {} \;
=== ./.terragrunt-cache/xK9mP2nQ8vR4/tY7wL1zB3cF6/backend.tf ===
terraform {
  backend "s3" {
    bucket         = "ecomarket-tfstate"
    key            = "ecomarket/prod/data/terraform.tfstate"
    region         = "eu-west-1"
    encrypt        = true
    dynamodb_table = "ecomarket-tfstate-locks"
  }
}

Warning. These generated files can contain resolved values, including secrets if your terragrunt.hcl interpolates them. It is the reason .terragrunt-cache/ is in .gitignore (07-02) and the reason they are not published as CI artefacts.

# 4. Drop down to pure Terraform. THE technique that separates the two layers.
cd .terragrunt-cache/*/*/
terraform plan

If it fails here too, the problem is Terraform's and everything in this lesson applies directly. If it does not fail here, the problem is Terragrunt's: the generation, the dependency blocks, or the inputs.

16.2. Dependencies between units

Terragrunt's most confusing failure is a dependency whose output does not exist yet:

ERRO[0004] Module /home/joan/ecomarket-infra/live/prod/app has finished with an error:
Module /home/joan/ecomarket-infra/live/prod/data has finished with an error: exit status 1

Two modules in the message and no hint as to which is the cause. The correct reading: the one that really failed is the last, data; app fails because it depended on it.

# See the dependency graph between units:
terragrunt graph-dependencies | dot -Tsvg > dependencies.svg

# Or run ONLY the failing unit, without the orchestration:
cd live/prod/data && terragrunt plan

And the case of mock_outputs, which hides errors until apply:

dependency "network" {
  config_path = "../network"

  # These fake values allow planning before 'network' exists.
  # And they are also why a "correct" plan fails at apply time
  # with "subnet-fake does not exist".
  mock_outputs = {
    vpc_id          = "vpc-00000000000000000"
    private_subnets = ["subnet-00000000000000000"]
  }

  # THIS is what avoids the problem: the mocks are only valid for validate
  # and validation plans, never for a real apply.
  mock_outputs_allowed_terraform_commands = ["validate", "plan"]
  mock_outputs_merge_strategy_with_state   = "shallow"
}

If you see IDs with lots of zeros in a plan, you are looking at mocks, not reality.

  1. Summary table: symptom → tool

Symptom First tool Command
"What does this expression evaluate to?" terraform console terraform console → type the expression
"Which outputs does this module have?" terraform console keys(module.network)
"Why is it replacing this resource?" Plan JSON jq '.resource_changes[] | select(...) | .change.replace_paths'
"What is unknown and why?" Plan JSON jq '... .change.after_unknown' + .configuration ... .references
"Which .tfvars was applied?" Plan JSON jq '.variables'
"Does this argument exist in my version?" The schema terraform providers schema -json | jq ...
"Who requires this provider version?" terraform providers terraform providers
"Why is there a cycle?" terraform graph terraform graph | grep <resource>
"What does Terraform ask the API for?" TF_LOG TF_LOG_PROVIDER=DEBUG + grep REQUEST POST-SIGN
"The apply is hanging" plan -json or gaps apply -json | jq 'select(.type=="apply_progress")'
"Terraform has blown up" crash.log Search for the panic's function in the issues
"Which module code is running?" modules.json jq '.Modules[]' .terraform/modules/modules.json
"It fails in CI and not locally" Reproduce the runner ci/reproduce-runner.sh <environment>
"Where does this input come from?" (Terragrunt) render-json terragrunt render-json --terragrunt-json-out /tmp/r.json
"Is it Terragrunt's or Terraform's?" Drop into the cache cd .terragrunt-cache/*/*/ && terraform plan
"The error points at a file I did not write" The path .terraform/modules/ or .terragrunt-cache/ → §13, §16

Common Mistakes and Tips

Starting with TF_LOG=TRACE. It is the instinctive reaction and almost always the wrong one: you generate 45,000 lines for a question terraform console answers in two seconds. Tip: walk the tree of §1. The cheap tools solve 70% of cases and none of them leaks secrets.

Using TF_LOG=DEBUG without TF_LOG_PATH. The traces go to stderr and get mixed in with the plan's output, which becomes unreadable. Tip: TF_LOG_PATH always, to a timestamped file, in a directory you can delete wholesale.

Forgetting that TF_LOG_PATH appends to the end of the file. Two runs write to the same place and you end up debugging the one from half an hour ago. Tip: rm -f "$TF_LOG_PATH" before each attempt, or a different name per run.

Pasting the whole trace into an issue or the team chat. It contains X-Amz-Security-Token, which is a credential valid for an hour, and user_data, which contains the startup configuration. Tip: funnel down to 12 lines, apply the filter of §6, and read the result before publishing it.

Believing the secret filter is enough. A sed script knows about the fields somebody thought to include; the sensitive attribute your provider does not mark as sensitive is still there. Tip: after filtering, run grep -iE 'password|secret|token|key|credential' and read every match.

Publishing the complete plan JSON as a PR artefact. terraform show -json reveals sensitive values in the clear, including var.db_password. Tip: publish a summary extracted with jq; the complete JSON stays on the runner.

Leaving terraform console open against production. It acquires the state lock, and the other team's deployment fails with a Who that is you. Tip: exit when you are done; and if you are going to explore for a while, terraform state pull > copy.tfstate and terraform console -state=copy.tfstate.

Leaving debugging probes in the code. An output "debug_..." that reaches main is stored in the state and is readable by anyone with access to the bucket. If it printed a secret, the secret is now in the production state. Tip: the debug_ prefix, and a CI check that fails if it finds one.

Isolating a module with a different provider version. The reproduction reproduces nothing and you conclude the module is fine. Tip: pin the exact version (= 5.62.0) in the isolation directory, taken from terraform version in the environment that fails.

Bisecting by changing two things at once. If it stops failing, you do not know which it was. Tip: one change per iteration, Git from the very first moment, and a two-line record per iteration.

Confusing terraform show -json with terraform plan -json. The first gives you the complete plan as an object; the second a stream of events during execution. Tip: to analyse the result, show; to follow progress or capture diagnostics, plan -json.

Looking for a CI failure in the code. If it does not reproduce locally, the code is not the problem: the differences are. Tip: ci/reproduce-runner.sh with the same image, the same version and the same role. Fifteen minutes per attempt becomes fifteen seconds.

Reading Terragrunt's mocks as reality. A "correct" plan full of subnet-00000000000000000 is not planning anything real. Tip: mock_outputs_allowed_terraform_commands = ["validate", "plan"] so they never reach an apply, and be suspicious of any ID with lots of zeros.

Exercises

Exercise 1: designing the funnel

EcoMarket's prod pipeline failed last night. The job was cancelled after 45 minutes by the runner's timeout, and all that is left is the trace the debugging step uploaded as an artefact: trace-prod-9182.log, 38,400 lines.

Write the complete sequence of commands to reduce trace-prod-9182.log to the fragment that explains the failure, without yet knowing which resource caused it. Justify each step and say what you expect to get from it.

Then answer: if the job was cancelled by a timeout and not by an error, what changes in your strategy compared with a log that ends in [ERROR]?

Exercise 2: the inexplicable replacement

The staging plan proposes replacing aws_db_instance.main. The team swears only a tag was changed. You have plan.tfplan.

  1. Write the jq query that answers exactly which attribute forces the replacement.
  2. Write the query that shows that attribute's value before and after.
  3. If replace_paths were empty but the actions were ["delete","create"], what would that mean and where would you look for the cause?
  4. The replacement is going to happen in prod next week. What is the practical difference between ["create","delete"] and ["delete","create"], and how do you get the first?

Exercise 3: instrumenting somebody else's module

The ecomarket-platform v3.4.0 module produces this error in the prod plan, and only in prod:

╷
│ Error: Invalid index
│
│   on .terraform/modules/platform/modules/app/load_balancer.tf line 61, in resource
│   "aws_lb_listener_rule" "services":
│   61:   priority = local.priorities[each.key]
│     ├────────────────
│     │ each.key is "checkout"
│     │ local.priorities is object with 3 attributes
│
│ The given key does not identify an element in this collection value.
╵

It works in dev and staging. The module is not yours, but you have read access to the repository.

  1. What does the ├──── block tell you and what hypothesis does it generate?
  2. Why is terraform console not enough here, and what would you do instead?
  3. Design the minimal reproduction: write the isolation directory's main.tf and say what you expect from each possible outcome.
  4. If the reproduction confirms it is a module bug, what would you include in the issue so that it can be fixed with no further questions?

Solutions

Solution 1

The sequence:

LOG=trace-prod-9182.log

# --- Step 0: orientation. What am I looking at?
wc -l "$LOG"
head -3 "$LOG"; tail -3 "$LOG"
# I expect: to confirm the Terraform and provider versions in the first
# lines, and to see HOW the file ends. An abrupt end mid-line
# confirms the process was killed, not that it finished.

# --- Step 1: are there any errors at all?
grep -c '\[ERROR\]' "$LOG"
grep '\[ERROR\]' "$LOG" | head -5 | cut -c1-160
# I expect: on a timeout, probably 0. That result is informative,
# not disappointing: it rules out a failure and confirms a hang.

# --- Step 2: the resource map.
grep -o 'tf_resource_type=[a-z0-9_]*' "$LOG" | sort | uniq -c | sort -rn | head
# I expect: the resource with the most lines is usually the one that got stuck,
# because retries and polling generate repeated traffic.

# --- Step 3: THE KEY STEP for a timeout. Time gaps.
awk '{ if (match($0,/^[0-9-]+T[0-9:.]+Z/)) {
         ts=substr($0,RSTART,RLENGTH); split(substr(ts,12,12),t,":")
         s=t[1]*3600+t[2]*60+t[3]
         if (p!="" && s-p>10) printf "%7.1fs before: %s\n", s-p, substr($0,1,140)
         p=s } }' "$LOG"
# I expect: one or more large gaps. The last gap before the end of
# the file is where it hung.

# --- Step 4: the last lines BEFORE the cut-off.
tail -60 "$LOG"
# I expect: the operation in progress. On a timeout this is more
# revealing than any grep, because it is literally what it was
# doing when it got killed.

# --- Step 5: isolate that operation.
ID=$(tail -200 "$LOG" | grep -o 'tf_req_id=[a-f0-9-]*' | tail -1 | cut -d= -f2)
grep "$ID" "$LOG" > /tmp/operation.log
wc -l /tmp/operation.log
grep -A25 'REQUEST POST-SIGN\|RESPONSE' /tmp/operation.log
# I expect: the request that never got a response, or a sequence of
# polling responses that never reach the final state.

What changes with a timeout compared with an error. The funnel's anchor changes, and that is the important part:

A log ending in [ERROR] A log cut off by a timeout
Anchor The error's line, and its tf_req_id The end of the file and the largest time gap
Main tool grep '[ERROR]' → tf_req_id The gaps awk and tail
Question "What did the API answer?" "What did not answer?"
Telltale pattern A 4xx/5xx response A request with no response, or polling that repeats without converging

And there is one very common concrete pattern this analysis uncovers: dozens of identical DescribeDBInstances calls every ten seconds, with the same "DBInstanceStatus": "modifying" response. That is not Terraform hanging: it is AWS taking longer than the configured timeouts. The fix is to raise the resource's timeout, not to retry the job.

Solution 2

1. Which attribute forces the replacement:

terraform show -json plan.tfplan \
  | jq -r '.resource_changes[]
           | select(.address == "aws_db_instance.main")
           | {
               actions: .change.actions,
               forces: [.change.replace_paths[]? | join(".")]
             }'
{
  "actions": ["delete", "create"],
  "forces": ["db_subnet_group_name"]
}

It was not the tag: it is db_subnet_group_name. And that has a likely explanation the team did not see: somebody changed the subnet group's name, or the group is being recreated because the network module's subnet list changed order. The tag change is real and harmless; what replaces the database is something else that travelled in the same PR.

2. The value before and after:

terraform show -json plan.tfplan \
  | jq -r '.resource_changes[]
           | select(.address == "aws_db_instance.main")
           | .change
           | {before: .before.db_subnet_group_name,
              after: (.after.db_subnet_group_name // "(unknown)"),
              is_unknown: (.after_unknown.db_subnet_group_name // false)}'
{
  "before": "ecomarket-staging-db-subnets",
  "after": "(unknown)",
  "is_unknown": true
}

The new value is unknown, which means the subnet group is also being recreated in this plan. The complete causal chain: something changed in module.network → aws_db_subnet_group is recreated → its name is unknown → aws_db_instance is replaced. To see it end to end:

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

3. If replace_paths were empty with actions ["delete","create"]. It would mean the replacement is not forced by any attribute, and there are three possible causes:

  • terraform taint or -replace=: somebody marked the resource for replacement explicitly. You check it by looking at the command that generated the plan.
  • A change of provider or of for_each/count that changes the resource's address: it is not an attribute-driven replacement, it is that that instance ceases to exist and another is born with a different key.
  • replace_triggered_by in the lifecycle block: the replacement is triggered by a change in another resource.

Where to look: jq '.configuration.root_module.resources[] | select(.address=="...") | .expressions.lifecycle' and the exact command that produced the plan.

4. ["create","delete"] versus ["delete","create"].

["create","delete"] ["delete","create"]
Real order Creates the new one, then deletes the old Deletes the old, then creates the new
Service outage None or minimal The whole creation time. For Multi-AZ RDS, 20-40 minutes
Produced by lifecycle { create_before_destroy = true } The default behaviour
Constraint Both exist at once: unique names collide —

You get it with:

resource "aws_db_instance" "main" {
  # The name must be able to coexist: a random suffix.
  identifier = "${local.prefix}-db-${random_pet.suffix.id}"

  lifecycle {
    create_before_destroy = true
  }
}

And the professional answer to this specific case: do not apply this in prod. Replacing the production database is not a Terraform operation, not even with create_before_destroy: the new instance is born empty. prevent_destroy is in place precisely so that this plan fails (09-01 §9.6), and the correct action is to split the PR and find out why the subnet group is being recreated.

Solution 3

1. What the ├──── block says and the hypothesis.

Two concrete data points and a contradiction:

  • each.key is "checkout" — it is iterating over a service called checkout.
  • local.priorities is object with 3 attributes — the priorities map inside the module has three entries.

The contradiction: the module iterates over a list of services that in prod includes checkout, but its internal local.priorities has only three keys. The module assumes the set of services is the one it knows about, probably because local.priorities is written by hand with the three keys of dev/staging.

Main hypothesis: the module has a locals with fixed priorities and the for_each comes from an input variable. As soon as you pass a service the module did not anticipate, the index fails. It is a module bug: a hidden coupling between a variable input and an internal constant.

Secondary hypothesis to rule out: that prod's var.services has a misspelled service. It is ruled out by comparing the .tfvars.

2. Why terraform console is not enough.

For two reasons, and both are limitations from §7.5:

  1. each.key does not exist in the console. The failing expression lives inside a block with for_each, and the console has no such context.
  2. local.priorities is internal to the module. The console only sees a module's outputs, never its locals. module.platform.local.priorities is not a valid expression.

What you can do from the console, and it is worth doing before anything else:

> keys(var.services)
[
  "api",
  "checkout",
  "web",
  "worker",
]

Four services in prod against three priorities in the module. Hypothesis confirmed without leaving the console, and without having read the module.

And then, read the real code, which is the technique of §13.1:

grep -n -B5 -A12 "priorities" \
  .terraform/modules/platform/modules/app/load_balancer.tf
14-locals {
15-  # TODO: make this configurable
16-  priorities = {
17-    web    = 100
18-    api    = 200
19-    worker = 300
20-  }
21-}
--
61:  priority = local.priorities[each.key]

The TODO on line 15 is the confession. The bug is located and documented by its own author.

3. The minimal reproduction.

# /tmp/isolate-platform/main.tf
# Reproduction of: aws_lb_listener_rule fails when var.services
# contains a key that is not in the module's local.priorities.
# ecomarket-platform v3.4.0, aws provider 5.62.0.

terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "= 5.62.0"     # the SAME as in prod; without this it does not reproduce
    }
  }
}

provider "aws" {
  region = "eu-west-1"
  # Nothing is going to be applied: we only need the PLAN to fail.
  skip_credentials_validation = true
  skip_requesting_account_id  = true
  skip_metadata_api_check     = true
  access_key                  = "fake"
  secret_key                  = "fake"
}

module "app" {
  source = "git::ssh://[email protected]/ecomarket/terraform-aws-ecomarket-platform.git//modules/app?ref=v3.4.0"

  prefix  = "reproduction"
  vpc_id  = "vpc-00000000000000000"
  subnets = ["subnet-00000000000000000", "subnet-00000000000000001"]
  tags    = {}

  # THE VARIABLE THAT TRIGGERS THE FAILURE: a fourth service.
  # With only web/api/worker, the plan works.
  services = {
    web      = { port = 8080, path = "/*" }
    api      = { port = 8081, path = "/api/*" }
    worker   = { port = 8082, path = "/worker/*" }
    checkout = { port = 8083, path = "/checkout/*" }   # ← this one
  }
}
cd /tmp/isolate-platform && terraform init && terraform plan

The three outcomes and how to read them:

Outcome Conclusion Next step
Fails with the same Invalid index A module bug, reproduced in 30 lines, with no real credentials and without your infrastructure Report it (point 4), and deploy the workaround
Does not fail Something in your context matters: another aliased provider, another version, another input Add context one item at a time until it fails
Fails with a different error before getting there Mandatory inputs are missing or the fake provider is not enough Fill in the minimum inputs; if a data is needed, replace it with a literal

A note on the provider with fake credentials: it works because a plan that fails during expression evaluation does so before calling the API. It is a very useful trick for reproducing core errors without touching any cloud, and it is worth bearing in mind for 09-04: an issue that reproduces without credentials is an issue the maintainer can run.

The workaround while the module is being fixed, which is what unblocks prod today:

# infra/app/modules.tf
# TEMPORARY WORKAROUND — module v3.4.0 has a fixed local.priorities with
# only 3 services (modules/app/load_balancer.tf:16). Issue
# ecomarket/terraform-aws-ecomarket-platform#212.
# Remove when v3.5.0 ships. Review: 2026-10-15.
module "app" {
  source  = "ecomarket/ecomarket-platform/aws//modules/app"
  version = "~> 3.0"

  services = {
    for k, v in var.services : k => v
    if contains(["web", "api", "worker"], k)
  }
  # ...
}

# 'checkout' is declared outside the module until v3.5.0 supports it.
resource "aws_lb_listener_rule" "checkout" {
  listener_arn = module.app.listener_arn
  priority     = 400
  # ...
}

4. What to include in the issue.

This is the bridge to 09-04, and the criterion is: everything that prevents a follow-up question.

  1. A specific title, with the symptom and the condition: "aws_lb_listener_rule: Invalid index in local.priorities when var.services has an unanticipated key".
  2. Exact versions: module v3.4.0, Terraform 1.9.5, AWS provider 5.62.0. Copied from terraform version, not from memory.
  3. The complete reproduction from point 3, verbatim, in a code block. With fake credentials, so that the maintainer can run it without an AWS account.
  4. The expected versus observed behaviour: "Expected: the module accepts any set of services, or validates the input with a clear message. Observed: Invalid index on an internal line of the module".
  5. The literal error message, with the .terraform/modules/... path included, because it points at the exact file and line.
  6. The cause, if you have located it: "modules/app/load_balancer.tf:16 defines local.priorities with three fixed keys and a TODO; line 61 indexes it with each.key, which comes from var.services".
  7. What you have already tried: "With only web/api/worker it works. It does not depend on the provider version: reproduced with 5.55.0 and 5.62.0".
  8. A proposed fix, because it turns the issue into a PR that is almost written: derive the priorities from var.services with index(), or add a validation that gives a comprehensible message.
  9. No secrets. The reproduction uses vpc-000..., fake credentials and the name reproduction. There is nothing to scrub because it was built without anything real.

Point 9 is not an afterthought: it is the result of having done point 3 properly. A good minimal reproduction is, by construction, a reproduction with no secrets.

Conclusion

This lesson has been the toolbox, and its underlying message is that debugging Terraform is not about reading more, but about looking in the right place with the cheapest tool that answers the question.

  • The tools have an order. terraform console, the plan in JSON and providers schema -json run nothing, lock nothing and leak nothing, and between the three of them they solve most diagnoses. TF_LOG=TRACE is the last option, not the first.
  • TF_LOG has five levels and DEBUG is almost always the right one, because it is where the HTTP requests and responses appear. TRACE adds the graph walk, which only matters for cycles, hangs and core bugs. And TF_LOG_CORE / TF_LOG_PROVIDER separately remove half the noise before you start.
  • The funnel is always the same: level and origin, resource, phase, tf_req_id, request and response. Five steps that turn 41,800 lines into 12. And when the log ends not in an error but in a timeout cut-off, the anchor changes: the time-gaps awk and the last sixty lines say more than any grep.
  • A trace is a dangerous file. It contains X-Amz-Security-Token, which is a credential valid for an hour; user_data, which is your startup configuration; and every value the provider does not mark as sensitive. The filter reduces the risk, it does not eliminate it: afterwards you have to read. And what you share is the minimal fragment, never the file.
  • terraform console is a debugger with access to the state, not a calculator. keys(module.network) settles the Unsupported attribute of an undeclared output in one second, and checking a for_each before writing it prevents the unknown-values error. In exchange, it locks the state: do not leave it open against production.
  • The plan in JSON is the most under-used tool. replace_paths says exactly which attribute forces a replacement, even when it is nested; after_unknown combined with .configuration ... .references closes the unknown-values diagnosis without reading a trace; and .variables ends any argument about which .tfvars was applied. In exchange, it reveals secrets in the clear: publish a summary, not the file.
  • terraform plan -json is a different thing: a stream of events during execution. apply_progress with its elapsed_seconds is what distinguishes a hung apply from an RDS instance that takes ten minutes, and that distinction is what stops you cancelling a job and creating an orphaned lock.
  • providers schema -json turns "I don't know whether this argument exists" into a fact in ten seconds, and with it half a family of errors from the previous catalogue disappears.
  • For somebody else's module, modules.json is the map: logical address, physical path and the exact version downloaded. And the minimal reproduction in an isolated directory — same provider version, literal values, no backend, with fake credentials if necessary — is what turns "the module fails" into something another person can run.
  • Reproducing the runner locally breaks the fifteen-minutes-per-attempt cycle. Same image, same version, same role, clean container. It is half an hour of writing a script and it pays for itself on the first day.
  • And a good minimal reproduction is, by construction, a reproduction with no secrets. That is the bridge to the module's last lesson.

There remains the class of problem none of these tools fixes: when what is broken is neither the code nor the provider, but the state. A lock left orphaned after somebody cancelled a job; an apply that died halfway and left half an environment created; a corrupt state file; a resource that exists in the cloud and that Terraform knows nothing about; two states that each believe they own the same resource. TF_LOG does not help there, because there is nothing to debug: you have to recover, and that has procedures, not tools.

The next lesson, State Management Issues, is those procedures: the checklist you answer in writing before a force-unlock, how to know what was left created after an interrupted apply, the three routes for recovering a corrupt state in order of preference — with the serial and lineage checks you must do before a state push that overwrites without asking — the systematic detection of orphaned resources with a script for EcoMarket, the drift that reappears on every plan, and the worst scenario of all: two states managing the same resource, with its chronology and its resolution procedure.

© Copyright 2026. All rights reserved