Module 8 ended with a sentence worth rereading before we start: "Once everything is automated, failures stop happening on your laptop. They happen on an ephemeral runner, with no TTY, no colours, none of your AWS profile, none of your provider cache and none of your shell history; in a container that was destroyed twenty minutes ago and of which only a 4,000-line log remains. [...] Knowing how to read those failures is a different skill from knowing how to build the pipeline, and it is the one that separates someone who has a machine that works from someone who has a machine nobody knows how to fix."
This lesson is both the catalogue and the method. The catalogue covers the errors that genuinely show up, with their literal message, their real cause — which is almost never the one the message seems to state — and their fix. The method is what you do before you look at the catalogue, and it is what separates half an hour of diagnosis from three hours of trying things at random.
There is one idea running through the whole lesson, and it is worth making explicit from the start: a Terraform error message describes where something broke, not why. The line that appears in the error is where the check failed, and the cause is usually somewhere else: in a .tfvars you never read, in a provider version that changed, in an organisational policy two levels above your account, or in a module you downloaded and never opened. Learning to debug Terraform is, to a large extent, learning not to believe the first line of the message.
Warning. In this lesson you will see error messages containing ARNs, account identifiers and resource names. They all belong to EcoMarket's fictitious accounts (
123456789012fordev,...13forstaging,...14forprod). When you paste a real error into a ticket, a chat or an issue, strip the identifiers you do not need: a full ARN reveals your organisation's account number, region and naming scheme. The full treatment of this is in 09-02 and 09-04.
- Anatomy of a Terraform error message
Terraform has a highly structured diagnostic format, and almost nobody reads it all the way through. Most people read the first line, decide they already know what is going on, and get it wrong. Let us take one apart piece by piece.
╷ │ Error: Unsupported argument │ │ on infra/data/datastore.tf line 42, in resource "aws_db_instance" "main": │ 42: allocated_storage_gb = local.current.storage_gb │ │ An argument named "allocated_storage_gb" is not expected here. Did you mean │ "allocated_storage"? ╵
Five parts, and each one carries a different kind of information:
| Part | Content in the example | What information it actually carries |
|---|---|---|
The box (╷ │ ╵) |
The border characters | Delimits one single diagnostic. If you see three boxes, those are three independent errors, not one error with three paragraphs |
| Severity and summary | Error: Unsupported argument |
The category of the failure, not the cause. This is the string you will search for on Google and in the issue tracker (09-04) |
| The source reference | on infra/data/datastore.tf line 42, in resource "aws_db_instance" "main" |
Where it was detected, which is not always where the cause lives. The named block is the lexical scope, useful when the file is large |
| The configuration snippet | 42: allocated_storage_gb = ... |
The exact line as Terraform read it. If it does not match what you are looking at, you are looking at a different file or a different branch |
| The detail | An argument named ... Did you mean "allocated_storage"? |
The explanation and, with luck, the suggestion. This is the part most people do not read |
The variants of the source block
Not every error carries the same source information, and the differences are significant.
Variant 1: with resolved values. When the error depends on the value of an expression, Terraform adds a section marked with ├──────────────── showing what that expression actually evaluated to. It is free information, and extremely valuable:
╷ │ Error: Invalid index │ │ on infra/app/compute.tf line 31, in resource "aws_instance" "bastion": │ 31: subnet_id = module.network.private_subnets[3] │ ├──────────────── │ │ module.network.private_subnets is list of string with 3 elements │ │ The given key does not identify an element in this collection value: the given │ index is greater than or equal to the length of the collection. ╵
The line module.network.private_subnets is list of string with 3 elements tells you, without your having to run anything, that the module returned three subnets and you asked for the fourth. In 09-02 you will see how to get that same information before it fails, using terraform console.
Variant 2: with with, in apply-phase errors. When the error comes from an API call during apply, the order changes: first the provider's message, then the resource:
╷
│ Error: creating RDS DB Instance (ecomarket-prod-db-noble-bee): operation error RDS:
│ CreateDBInstance, https response error StatusCode: 400, RequestID:
│ 4c0e2f1a-9b77-4d31-8e5c-6f2a91d0b3e8, api error InvalidParameterValue: Invalid
│ DB engine version 16.9 for postgres
│
│ with aws_db_instance.main,
│ on infra/data/datastore.tf line 30, in resource "aws_db_instance" "main":
│ 30: resource "aws_db_instance" "main" {
│
╵Notice the difference: here the summary is not a Terraform category (Unsupported argument) but the text the AWS API returned, wrapped by the provider. The structure is always the same and it is worth learning:
creating RDS DB Instance (NAME): operation error SERVICE: OPERATION, https response error StatusCode: CODE, RequestID: ID, api error ERROR_CODE: MESSAGE
creating RDS DB Instance: what the provider was doing. If it sayscreating, the resource did not exist; if it saysupdating, it did exist and the modification failed; if it sayswaiting for, it was created and the failure happened while waiting for it to become ready — an important case, because the resource does exist, and we will come back to it in 09-03.operation error RDS: CreateDBInstance: the exact API call. This is what you will look up in the AWS documentation, not in Terraform's.StatusCode: 400: a4xxmeans the request is at fault (yours); a5xxbelongs to the service and usually deserves a retry.RequestID: the identifier the cloud provider's support team will ask you for. Keep it.api error InvalidParameterValue: the API error code, which is the term to search for, not the English sentence that follows it.
Variant 3: with no source. Some errors have no file and no line because they do not belong to any:
╷ │ Error: Backend configuration changed │ │ A change in the backend configuration has been detected, which may require │ migrating existing state. ╵
The absence of a source is itself a clue: the problem is not in the code, it is in the execution environment — the backend, the credentials, the .terraform/ cache.
Warnings versus errors
Terraform uses the same box for Warning:, and the practical difference is that a warning does not stop execution. In a 4,000-line CI log, a warning is buried and nobody sees it until it turns into an error two versions later:
╷ │ Warning: Argument is deprecated │ │ with aws_s3_bucket.images, │ on infra/data/datastore.tf line 12, in resource "aws_s3_bucket" "images": │ 12: acl = "private" │ │ Use the aws_s3_bucket_acl resource instead ╵
Operational tip for EcoMarket: the pipeline from 08-01 posts the plan on the PR. Add a warning counter to the posting script and put it in the headline. A visible ⚠ 14 warnings is what stops you discovering fourteen deprecations on the day of the provider's major upgrade.
# Count warnings in the structured plan output (see 09-02 for the detail).
terraform plan -json -out=plan.tfplan \
| jq -r 'select(.type=="diagnostic" and .diagnostic.severity=="warning")
| .diagnostic.summary' \
| sort | uniq -c | sort -rnWhat this command does, step by step:
terraform plan -jsonemits one JSON line per event instead of text for humans.jq -r 'select(...)'keeps only events of typediagnosticwhose severity iswarning..diagnostic.summaryextracts the summary, which is the stable part of the message.sort | uniq -c | sort -rngroups them: instead of fourteen loose lines you get "11 × Argument is deprecated, 3 × Value for undeclared variable".
- The five-step diagnostic method
Before you look the error up in any catalogue, answer five questions. It takes two minutes and it removes most of the search space.
flowchart TD
A["Terraform has failed"] --> B{"1. Which phase?"}
B -->|init| C["Providers, versions,<br/>backend, modules<br/>→ §4"]
B -->|validate| D["Syntax, types,<br/>references<br/>→ §5, §6"]
B -->|plan| E{"2. Who emits<br/>the message?"}
B -->|apply / destroy| E
E -->|"An English category<br/>like 'Unsupported argument'"| F["Terraform CORE<br/>→ §5, §6, §7, §10"]
E -->|"'operation error X:'<br/>'api error Y:'"| G["Cloud provider API<br/>→ §8, §9"]
E -->|"'This is a bug in the provider'"| H["PROVIDER<br/>→ §10"]
F --> I{"3. Does it reproduce<br/>locally?"}
G --> I
H --> I
I -->|No| J["It belongs to the environment:<br/>version, credentials,<br/>cache, clock → §12"]
I -->|Yes| K{"4. What changed since<br/>the last time it worked?"}
K --> L["git log of the code<br/>+ lock file<br/>+ provider version<br/>+ changes in the cloud"]
L --> M["5. Reduce to the smallest case<br/>that reproduces it"]
M --> N["Fix it, or report it<br/>with the reproduction → 09-04"]
style B fill:#dbeafe,stroke:#1d4ed8
style E fill:#dbeafe,stroke:#1d4ed8
style I fill:#dbeafe,stroke:#1d4ed8
style K fill:#dbeafe,stroke:#1d4ed8
style H fill:#fee2e2,stroke:#b91c1c
style J fill:#fef3c7,stroke:#b45309
Step 1: which phase is failing?
This is the question that narrows things down the most, and the one most people skip because they assume they know the answer. The phase determines what information existed at the moment of failure:
| Phase | What has already happened | What has not happened | What can fail here |
|---|---|---|---|
init |
Nothing. The state has not even been read | No expression has been evaluated | Downloading providers and modules, backend configuration, lock file |
validate |
All the HCL has been parsed | There is no state, no credentials, no variable values | Syntax, static types, references to undeclared things |
plan |
The state was read, refreshed against the cloud, expressions were evaluated | Nothing has been created or modified | Unknown values, preconditions, data sources, read permissions |
apply |
Everything above, plus writing to the real world | The final state has not been written yet | Write permissions, quotas, name conflicts, timeouts, provider consistency |
destroy |
The reverse dependency order was computed | — | prevent_destroy, external dependencies that block deletion, resources already deleted by hand |
The most useful consequence: if it fails in plan, you have not touched anything. You can experiment freely. If it fails in apply, part of the world has been modified and part has not, and the first thing to find out is not why it failed but what was left half-done (09-03).
Step 2: is it core, the provider or the API?
Three different origins, three different places to look, three kinds of fix.
| Origin | How to recognise it | Where it gets fixed | Where it gets reported |
|---|---|---|---|
| Terraform core | A summary that is a language category: Unsupported argument, Cycle, Invalid for_each argument, Inconsistent conditional result types |
In your HCL, almost always | hashicorp/terraform |
| Provider | This is a bug in the provider, or behaviour that contradicts its documentation |
A different version, ignore_changes, a temporary workaround |
terraform-provider-aws, -azurerm, -google |
| Cloud API | operation error ..., api error ..., StatusCode:, RequestID: |
In the cloud: permissions, quotas, valid parameters | AWS/Azure/GCP support, not Terraform |
This step matters because it determines who you are asking the question of. An AccessDenied is not a Terraform problem and it is not solved by reading Terraform documentation; a Cycle is not an AWS problem and it is not solved by opening a support ticket.
Step 3: does it reproduce locally?
# Minimal local reproduction, with the same backend and the same variables
# EcoMarket's pipeline used.
cd infra/app
terraform init -backend-config=../../backends/staging.hcl -reconfigure
terraform plan \
-var-file=../../environments/common.auto.tfvars \
-var-file=../../environments/staging.tfvars \
-no-colorThree possible outcomes and three different conclusions:
- It fails the same way locally. Congratulations: the diagnostic cycle goes from fifteen minutes to fifteen seconds. Move on to step 4.
- It does not fail locally. The problem belongs to the environment, not the code. Go straight to §12.
- It fails differently locally. The difference is the clue. Almost always it is the Terraform or provider version; check it with
terraform versionin both places before going any further.
Careful with this. Reproducing locally with
-reconfigureagainst thestagingbackend means you are pointing atstaging's real state. Aplanis harmless, but it acquires the lock, and cancelling it brutally leaves that lock orphaned (09-03). If all you want is to reproduce a syntax or type error,terraform validatedoes not touch the backend at all.
Step 4: what changed since the last time it worked?
Four things may have changed, and only one of them is in your git log:
| What changed | How to check it | Frequency |
|---|---|---|
| Your code | git log --oneline -- infra/ modules/ environments/ |
High, and it is the first thing everybody looks at |
| The provider version | git diff HEAD~10 -- .terraform.lock.hcl, and terraform version |
High, and it is what almost nobody looks at |
| A module version | The version = "~> 3.0" that resolved to 3.4.0 this morning and to 3.5.0 now |
Medium, and invisible unless you look at modules.json |
| The cloud | Somebody changed something by hand, a new SCP, an exhausted quota, a change in the API itself | Medium, and the hardest to verify |
The command that most often settles this in under a minute:
# Did the provider version change between the last good deployment and this one?
git log --oneline -5 -- .terraform.lock.hcl
git diff HEAD~1 HEAD -- .terraform.lock.hclIf .terraform.lock.hcl changed and the error appeared afterwards, you have your prime suspect. Having the lock file under version control and having CI use -lockfile=readonly (08-01 §14) exists precisely so that this question has an answer.
Step 5: reduce to the smallest case that reproduces it
This step is not optional even though it looks like extra work, for three reasons: you almost always find the cause while reducing; if you do not find it, you now have the reproduction an issue needs (09-04); and if it turns out you cannot reduce it, you have already learned something important — the failure depends on context.
The procedure, spelled out in 09-02 as bisection:
- Copy the bare minimum into a new directory, with a local backend (
terraform { }with nobackendblock). - Replace module references with literal values.
- Remove half of the configuration. Does it still fail? Remove another half. Did it stop failing? Go back and remove the other half instead.
- Stop when ten lines are left or the failure disappears.
- Classifying errors by phase
The module's reference table. Keep it to hand; the rest of the lesson expands it section by section.
| Phase | Error summary | Most frequent real cause | Section |
|---|---|---|---|
init |
Failed to query available provider packages |
Provider name misspelled, or source missing |
§4.1 |
init |
no available releases match the given constraints |
Two version constraints with no intersection | §4.2 |
init |
Inconsistent dependency lock file |
required_providers changed and no init -upgrade was run |
§4.3 |
init |
Failed to install provider (checksum) |
Lock file with no hashes for the runner's platform | §4.3 |
init |
Backend configuration changed |
backends/<environment>.hcl changed, or environments got mixed |
§4.4 |
init |
Failed to download module |
Git credentials missing on the runner, or a non-existent ref |
§4.5 |
validate |
Unsupported argument |
An invented argument, a renamed one, or one from another provider version | §5.1 |
validate |
Unsupported block type |
A block moved to another resource in a major version | §5.2 |
validate |
Invalid value for input variable |
Incompatible type in .tfvars, usually inside var.environments |
§5.3 |
validate |
Invalid value for variable |
A validation block failed |
§5.3 |
validate |
Inconsistent conditional result types |
? : with a number and a string |
§5.4 |
validate |
Invalid index |
Index out of range or non-existent key | §5.5 |
validate |
Call to unknown function |
A function that does not exist in HCL, or a typo | §5.6 |
validate |
Reference to undeclared resource/input variable |
Renamed resource, undeclared variable, forgotten file | §6.1 |
validate |
Unsupported attribute |
Output not declared in the module, or attribute that does not exist in that version | §6.2 |
plan |
Cycle: ... |
Two resources referencing each other | §6.3 |
plan |
Invalid count argument |
count derived from an unknown attribute |
§7 |
plan |
Invalid for_each argument |
for_each keys derived from unknown attributes |
§7 |
plan |
AccessDenied in a data |
The plan role has no read permission | §8 |
apply |
AccessDenied / explicit deny in a service control policy |
SCP, permissions boundary or organisational policy | §8 |
apply |
EntityAlreadyExists / BucketAlreadyOwnedByYou |
Resource created outside Terraform, or an earlier half-finished apply | §9.2 |
apply |
RequestLimitExceeded / Throttling |
API rate limit | §9.3 |
apply |
InvalidParameterValue with an ID that does exist |
Eventual consistency: the resource is not visible yet | §9.4 |
apply |
timeout while waiting for state to become 'available' |
The resource takes longer than the configured timeout | §9.5 |
apply |
Provider produced inconsistent final plan |
Provider bug, or an attribute normalised by the API | §10 |
apply |
Provider produced inconsistent result after apply |
The same, detected after writing | §10 |
destroy |
Instance cannot be destroyed |
prevent_destroy is active |
§9.6 |
destroy |
DependencyViolation |
Something created outside Terraform depends on the resource | §9.6 |
init errors: providers, versions, backend and modules
init errors: providers, versions, backend and modulesinit fails before anything exists: there is no state, no evaluated expressions, not necessarily any cloud credentials. That is why its errors are almost always environment configuration problems, not logic problems.
4.1. Provider not found
╷ │ Error: Failed to query available provider packages │ │ Could not retrieve the list of available versions for provider │ hashicorp/awss: provider registry registry.terraform.io does not have a │ provider named registry.terraform.io/hashicorp/awss │ │ All modules should specify their required_providers so that external │ consumers will get the correct providers when using a module. To see which │ modules are currently depending on hashicorp/awss, run the following │ command: │ terraform providers ╵
What it actually says. hashicorp/awss does not exist. But notice the important detail: it does not say where it is declared. If you have six nested modules, that awss could be in any of them, which is why the message itself hands you the command.
Providers required by configuration:
.
├── provider[registry.terraform.io/hashicorp/aws] ~> 5.60
├── module.network
│ └── provider[registry.terraform.io/hashicorp/aws]
├── module.data
│ ├── provider[registry.terraform.io/hashicorp/aws]
│ └── provider[registry.terraform.io/hashicorp/random]
└── module.observability
└── provider[registry.terraform.io/hashicorp/awss]The tree points at the culprit: module.observability.
The most treacherous variant in this family is not the typo but the provider with no source. If you use a provider that is not HashiCorp's and you do not declare it in required_providers, Terraform assumes hashicorp/<name>:
# WRONG: Terraform will look for hashicorp/cloudflare, which does not exist.
resource "cloudflare_record" "www" {
# ...
}# RIGHT: the source says where it really lives.
terraform {
required_providers {
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 4.0"
}
}
}4.2. Version constraints with no intersection
╷ │ Error: Failed to query available provider packages │ │ Could not retrieve the list of available versions for provider │ hashicorp/aws: no available releases match the given constraints >= 4.0.0, │ ~> 5.0, < 5.0.0 ╵
What it actually says. There are three constraints and no version satisfies all three. ~> 5.0 means >= 5.0, < 6.0; < 5.0.0 contradicts it. The set is empty.
What the message does not say, and what you need: where those constraints come from. Every required_providers in every module contributes its own, and terraform providers shows you all of them:
At EcoMarket this happens when the ecomarket-platform ~> 3.0 module raises its provider floor in a minor version. It is one of the reasons why 04-05 insists that modules declare open floors (>= 5.0) and root configurations declare the ceiling (~> 5.60): if the module pins ~> 5.40 and your root pins ~> 5.60, it works; if the module pins ~> 4.0, there is no way out that does not involve upgrading the module.
4.3. Inconsistent lock file and checksums that do not add up
Two different errors that people confuse constantly.
The first: you changed the constraint and did not reinitialise.
╷ │ Error: Inconsistent dependency lock file │ │ The following dependency selections recorded in the lock file are inconsistent │ with the current configuration: │ - provider registry.terraform.io/hashicorp/aws: locked version selection │ 5.62.0 doesn't match the updated version constraints "~> 6.0" │ │ To update the locked dependency selections to match a changed configuration, │ run: │ terraform init -upgrade ╵
It is benign and the message carries its own fix. What matters is where it shows up: if it appears in the pipeline and not locally, it means somebody changed required_providers and did not update the lock file in the same commit. With -lockfile=readonly in CI, that PR fails at init, which is exactly what you want: the alternative is a pipeline that upgrades the provider silently.
The second: the lock file has no hashes for the runner's platform.
╷ │ Error: Failed to install provider │ │ Error while installing hashicorp/aws v5.62.0: the local package for │ registry.terraform.io/hashicorp/aws 5.62.0 doesn't match any of the checksums │ previously recorded in the dependency lock file (this might be because the │ available checksums are for packages targeting different platforms) ╵
What it actually says. The closing parenthesis is the whole message, and it is the only part that matters: your colleague generated the lock file on a MacBook (darwin_arm64) and the CI runner is linux_amd64. The hashes in the file do not cover the runner's platform.
# The fix, run ONCE and committed:
terraform providers lock \
-platform=linux_amd64 \
-platform=darwin_arm64 \
-platform=darwin_amd64At EcoMarket this lives in the CONTRIBUTING.md of the ecomarket-infra repository and in a pre-commit hook, because it is an error that shows up once per new joiner and costs half a morning if it is not documented.
4.4. Backend configuration changed
╷ │ Error: Backend configuration changed │ │ A change in the backend configuration has been detected, which may require │ migrating existing state. │ │ If you wish to attempt automatic migration of the state, use │ "terraform init -migrate-state". │ If you wish to store the current configuration with no changes to the state, │ use "terraform init -reconfigure". ╵
What it actually says, and why it is dangerous. Terraform has compared the backend you are asking for now with the one cached in .terraform/terraform.tfstate (the local file that remembers the last backend configuration, not the state). They differ. And it offers you two ways out that do opposite things:
| Option | What it does | When it is correct | Risk if you get it wrong |
|---|---|---|---|
-migrate-state |
Copies the state from the old backend to the new one | A real, planned backend migration | Writes one environment's state over another's |
-reconfigure |
Forgets the previous backend and uses the new one as-is | You switched environments in the same directory, or it is a fresh working directory | None for the state; you lose the local history |
At EcoMarket the number one cause is trivial and has nothing to do with migrating anything: you have just run terraform init -backend-config=backends/staging.hcl in a directory where you previously ran dev. What you want is -reconfigure. If you pick -migrate-state and accept, you have just copied dev's state over staging's key in S3.
Warning.
-migrate-statein the wrong directory is one of the fastest ways to produce the overlapping states of 09-03. Before accepting a migration, runterraform state listagainst the target backend: if it returns resources, stop.
The structural prevention, already used by the pipeline in 08-01: a clean working directory per run, or a different TF_DATA_DIR per environment:
# One .terraform/ per environment: inits never tread on each other.
export TF_DATA_DIR=".terraform-${ENVIRONMENT}"
terraform init -backend-config="backends/${ENVIRONMENT}.hcl" -reconfigure4.5. Module unreachable because of Git credentials
╷ │ Error: Failed to download module │ │ Could not download module "platform" (modules.tf:8) source code from │ "git::ssh://[email protected]/ecomarket/terraform-aws-ecomarket-platform.git?ref=v3.4.0": │ error downloading │ 'ssh://[email protected]/ecomarket/terraform-aws-ecomarket-platform.git?ref=v3.4.0': │ /usr/bin/git exited with 128: Cloning into '.terraform/modules/platform'... │ [email protected]: Permission denied (publickey). │ fatal: Could not read from remote repository. ╵
How to read it. The error has three layers and you have to get to the last one:
Failed to download module— the Terraform layer. Says nothing useful./usr/bin/git exited with 128— the Git layer. Nor does this one.Permission denied (publickey)— the real cause. Git has nothing to authenticate with.
The general rule: when a Terraform error contains the output of another program, the cause is in the innermost line, not the first one.
The four causes, in order of frequency on a runner:
| Exact symptom | Cause | Fix |
|---|---|---|
Permission denied (publickey) |
There is no SSH key on the runner, or it is not in the agent | A deploy key, or insteadOf with a token |
remote: Repository not found |
The token exists but has no access to the repository | Widen the token's scope; on GitHub Actions, an App token |
couldn't find remote ref v3.4.0 |
The tag does not exist (v3.4.0 versus 3.4.0?) |
git ls-remote --tags against the repository |
| Works locally, fails in CI | Your ~/.gitconfig has an insteadOf the runner does not have |
Replicate it in the pipeline's init step |
The last row is the classic §12 case and deserves the detail:
# On your laptop this has been sitting in ~/.gitconfig for months and you forgot:
# [url "[email protected]:"]
# insteadOf = https://github.com/
#
# On the runner, the equivalent with an ephemeral token:
git config --global url."https://oauth2:${MODULES_TOKEN}@github.com/".insteadOf \
"https://github.com/"
terraform init -backend-config="backends/${ENVIRONMENT}.hcl"Warning. That
git config --globalwrites the token into the runner's~/.gitconfig. On an ephemeral runner that is acceptable; on a persistent one — the Jenkins agents of 08-02 — it is a credential left on disk. Use per-processGIT_CONFIG_COUNT/GIT_CONFIG_KEY_0, or wipe the file when you are done.
- Syntax and type errors
These are the good errors: they are caught in validate, with no credentials and without touching anything, which is why EcoMarket's pipeline runs terraform validate before anything else. An error from this family costs seconds if CI is set up properly, and fifteen minutes if it is discovered during plan.
5.1. Unsupported argument
╷ │ Error: Unsupported argument │ │ on infra/data/datastore.tf line 42, in resource "aws_db_instance" "main": │ 42: allocated_storage_gb = local.current.storage_gb │ │ An argument named "allocated_storage_gb" is not expected here. Did you mean │ "allocated_storage"? ╵
Three causes, and only the first is the obvious one:
- A typo or an invented name. The
Did you meansettles it. - The argument exists, but in a different provider version. You wrote
manage_master_user_passwordfollowing the Registry documentation (which shows the latest version) and your lock file pins an earlier one. The message is identical and theDid you meaneither does not appear or suggests something absurd. - The argument exists, but on a different resource. Very common after the big AWS provider restructurings:
acl,versioning,lifecycle_ruleandserver_side_encryption_configurationleftaws_s3_bucketand now live in resources of their own.
How to tell cause 1 from cause 2 in ten seconds — the full method is in 09-02:
# Does this argument exist in the version I HAVE installed?
terraform providers schema -json \
| jq -r '.provider_schemas["registry.terraform.io/hashicorp/aws"]
.resource_schemas["aws_db_instance"].block.attributes
| keys[]' \
| grep -i masterIf manage_master_user_password does not appear, the argument does not exist in your version: the problem is the version, not the spelling, and the fix is to raise the provider, not to correct the line.
5.2. Unsupported block type
╷
│ Error: Unsupported block type
│
│ on infra/data/datastore.tf line 58, in resource "aws_s3_bucket" "images":
│ 58: lifecycle_rule {
│
│ Blocks of type "lifecycle_rule" are not expected here.
╵The same diagnosis as the previous one, applied to nested blocks. The dominant cause in 2025–2026 is still the split of aws_s3_bucket into independent resources that happened in version 4 of the AWS provider:
# BEFORE (aws provider v3):
resource "aws_s3_bucket" "images" {
bucket = "${local.prefix}-images-${random_pet.suffix.id}"
lifecycle_rule {
enabled = true
expiration { days = 90 }
}
}# NOW (aws provider v4+): the bucket and its lifecycle are two resources.
resource "aws_s3_bucket" "images" {
bucket = "${local.prefix}-images-${random_pet.suffix.id}"
tags = local.common_tags
}
resource "aws_s3_bucket_lifecycle_configuration" "images" {
bucket = aws_s3_bucket.images.id
rule {
id = "expire-originals"
status = "Enabled"
# In the modern provider an empty filter is mandatory if the rule
# applies to the whole bucket. Omitting it produces a different error.
filter {}
expiration {
days = 90
}
}
}The detail that costs an hour: filter {}. Without it, the provider returns Error: Invalid Attribute Combination or, worse, a Provider produced inconsistent final plan (§10). The empty block is not decorative: it means "this rule applies to every object", and the API requires it.
5.3. Invalid value for input variable and Invalid value for variable
Two similar messages with different causes.
The first is a type error, and at EcoMarket it almost always shows up in var.environments, which is a map(object(...)) with many fields:
╷
│ Error: Invalid value for input variable
│
│ on environments/prod.tfvars line 12:
│ 12: environments = {
│
│ The given value is not suitable for var.environments declared at
│ variables.tf:30,1-20: element "prod": attribute "multi_az": a bool is required.
╵How to read it. The source reference points at line 12, where the map starts, not where the error is. The detail does pin it down: element "prod": attribute "multi_az". That path — map element, then object attribute — is the useful information, and the more nested the type, the longer it gets:
element "prod": attribute "scaling": attribute "rules": element 2: attribute "threshold": a number is required.
You read it from the outside in, like a directory path: environments["prod"].scaling.rules[2].threshold.
The typical cause in a .tfvars:
# environments/prod.tfvars — WRONG
environments = {
prod = {
db_class = "db.r6g.xlarge"
storage_gb = 500
multi_az = "true" # ← a string, not a boolean
retention_days = 30
}
}HCL does not convert "true" to true inside an object with declared types. Outside an object it would convert; inside, it does not. It is an asymmetry that catches everybody out once.
The second is a validation failure, and it is an error you wrote:
╷ │ Error: Invalid value for variable │ │ on environments/prod.tfvars line 3: │ 3: environment = "production" │ ├──────────────── │ │ var.environment is "production" │ │ The environment must be one of: dev, staging, prod. │ │ This was checked by the validation rule at variables.tf:18,3-13. ╵
Here everything is useful information: the real value ("production"), your message, and the exact line of the rule. It is the best possible error, and it exists because somebody wrote the validation. It is a direct argument for the discipline of 02-02: every validation you write today is a readable error six months from now.
5.4. Inconsistent conditional result types
╷ │ Error: Inconsistent conditional result types │ │ on infra/data/locals.tf line 23, in locals: │ 23: retention = var.environment == "prod" ? 30 : "7" │ │ The true and false result expressions must have consistent types. The 'true' │ value is number, but the 'false' value is string. ╵
Literal and with no catch. The version that does have a catch is this one:
# Both arms are lists, but of DIFFERENT object types.
locals {
subnets = var.environment == "prod"
? [{ cidr = "10.0.1.0/24", az = "eu-west-1a" }]
: [{ cidr = "10.0.1.0/24", az = "eu-west-1a", public = true }]
}A message that appears to say the two are the same. They are not: the elements have different shapes. The fix is to make the shapes match, not the number of elements:
locals {
subnets = var.environment == "prod"
? [{ cidr = "10.0.1.0/24", az = "eu-west-1a", public = false }]
: [{ cidr = "10.0.1.0/24", az = "eu-west-1a", public = true }]
}5.5. Invalid index
╷ │ Error: Invalid index │ │ on infra/app/compute.tf line 31, in resource "aws_instance" "bastion": │ 31: subnet_id = module.network.private_subnets[3] │ ├──────────────── │ │ module.network.private_subnets is list of string with 3 elements │ │ The given key does not identify an element in this collection value: the given │ index is greater than or equal to the length of the collection. ╵
For maps the message changes and is more useful, because it lists the available keys:
╷ │ Error: Invalid index │ │ on infra/app/main.tf line 14, in locals: │ 14: current = var.environments["production"] │ ├──────────────── │ │ var.environments is map of object with 3 elements │ │ The given key does not identify an element in this collection value. ╵
The structural advice, which belongs to 02-01 but gets collected here: indexing by position is fragile. private_subnets[3] assumes an order the module does not guarantee. If the network module returns a map keyed by availability zone, the access is explicit and the error, if it happens, says which key is missing:
# Fragile: it depends on the order of the list.
subnet_id = module.network.private_subnets[0]
# Robust: it depends on a name, which is what you actually mean.
subnet_id = module.network.private_subnets_by_az["eu-west-1a"]5.6. Call to unknown function
╷ │ Error: Call to unknown function │ │ on infra/app/locals.tf line 12, in locals: │ 12: name = to_lower(var.project) │ │ There is no function named "to_lower". Did you mean "lower"? ╵
Two causes, and a third that no longer exists:
- Wrong name. The
Did you meanalmost always settles it. - The function belongs to a later Terraform version.
strcontains(1.5),templatestring(1.9),provider::(1.8). If yourrequired_versionallows 1.6 and CI runs 1.6, the function does not exist there even though it works on your laptop with 1.9. This is a pure §12 case. - Provider functions, from Terraform 1.8 onwards:
provider::aws::arn_parse(...). If the provider is not in that module'srequired_providers, this is the error you get.
- Reference errors and cycles in the graph
6.1. Reference to undeclared resource / input variable
╷ │ Error: Reference to undeclared resource │ │ on infra/app/load_balancer.tf line 88, in resource "aws_lb_target_group" "app": │ 88: vpc_id = aws_vpc.main.id │ │ A managed resource "aws_vpc" "main" has not been declared in the root │ module. ╵
The key phrase is in the root module. Terraform is telling you that it looked in the current module and did not find it. The four causes:
| Cause | Clue | Fix |
|---|---|---|
| The resource lives in another module | aws_vpc.main does exist, but inside module.network |
module.network.vpc_id, and declare the output (04-02) |
| The resource lives in another state | It exists in infra/network/, which is a separate terraform apply |
data "terraform_remote_state" (03-03) |
| You renamed it and forgot a reference | The PR's git diff shows it |
Fix it, and use moved if it is already applied (03-05) |
| The file that declares it is not in this directory | ls *.tf does not include it |
Terraform does not read subdirectories. Only the .tf files in the current directory |
The last one deserves emphasis because it surprises people coming from other languages: Terraform loads every .tf in the directory and none from its subdirectories. There is no import, no include. If network.tf sits in infra/app/components/, it does not exist as far as infra/app/ is concerned.
The variable flavour is just as direct and brings the fix in writing:
╷
│ Error: Reference to undeclared input variable
│
│ on infra/app/locals.tf line 14, in locals:
│ 14: prefix = "${var.project}-${var.environment}"
│
│ An input variable with the name "project" has not been declared. This variable
│ can be declared with a variable "project" {} block.
╵Watch out for the mirror image of this error, which is not an error but a warning and therefore goes unnoticed:
╷ │ Warning: Value for undeclared variable │ │ The root module does not declare a variable named "project_name" but a value │ was found in file "environments/prod.tfvars". If you meant to use this value, add a │ "variable" block to the configuration. ╵
This means there is a value in your .tfvars that Terraform is silently ignoring. At EcoMarket, with common.auto.tfvars loading automatically and one .tfvars per environment, it is the mechanism by which a production value stops being applied without anybody noticing. That is why the warning counter in §1 is not a whim.
6.2. Unsupported attribute, including the undeclared-output case
╷ │ Error: Unsupported attribute │ │ on infra/data/datastore.tf line 64, in resource "aws_db_subnet_group" "main": │ 64: subnet_ids = module.network.data_subnets │ ├──────────────── │ │ module.network is a object │ │ This object does not have an attribute named "data_subnets". ╵
This is the case 04-03 promised to pick up here, and it is the most misinterpreted of the lot.
The line module.network is a object is the key, and what nobody sees at first is what it does not say. A module, seen from outside, is not its code: it is exactly the set of its outputs. Even if modules/network/main.tf contains a perfectly well-defined aws_subnet.data, if there is no output "data_subnets", then as far as the outside world is concerned it does not exist.
The confusion arises because the module is yours and you have it open in the editor. You are staring at aws_subnet.data while Terraform tells you it does not exist, and the natural conclusion is that Terraform is wrong. It is not wrong: you are looking inside a box whose only visible surface is the list of outputs.
How to check the module's real surface, with no guesswork:
# Which outputs does the module I am using actually expose?
grep -rn "^output" modules/network/*.tf
# If the module is remote, it is downloaded here (see §11):
grep -rn "^output" .terraform/modules/platform/modules/network/*.tfThere is the answer in one line: there are three outputs and data_subnets is not one of them.
The other cause of Unsupported attribute, this time on resources rather than modules, is the provider version again:
╷ │ Error: Unsupported attribute │ │ on infra/data/outputs.tf line 8, in output "endpoints": │ 8: value = aws_db_instance.main.master_user_secret[0].secret_arn │ ├──────────────── │ │ aws_db_instance.main is object with 61 attributes │ │ This object does not have an attribute named "master_user_secret". ╵
object with 61 attributes tells you the resource exists and has 61 attributes; master_user_secret is not among them because a later provider version added it. Same diagnosis as §5.1: terraform providers schema -json.
6.3. Cycle: how to read it and how to break it
╷ │ Error: Cycle: aws_security_group_rule.app_to_db, aws_security_group.db, │ aws_security_group_rule.db_from_app, aws_security_group.app, │ aws_security_group_rule.app_to_db ╵
How to read it. It is a list of resource addresses where each depends on the next, and the last one is the first one again. Terraform does not know which to start with because every one of them needs another to exist first.
In this case the cycle is the classic one of mutually referencing security groups:
# CYCLE: each group needs the other's ID in order to exist.
resource "aws_security_group" "app" {
name = "${local.prefix}-app"
vpc_id = module.network.vpc_id
egress {
from_port = 5432
to_port = 5432
protocol = "tcp"
security_groups = [aws_security_group.db.id] # ← needs db
}
}
resource "aws_security_group" "db" {
name = "${local.prefix}-db"
vpc_id = module.network.vpc_id
ingress {
from_port = 5432
to_port = 5432
protocol = "tcp"
security_groups = [aws_security_group.app.id] # ← needs app
}
}The general solution for cycles: split the resource that closes the cycle into a piece that gets created afterwards. With security groups, AWS and the provider offer exactly that:
# The groups are created empty: neither depends on the other.
resource "aws_security_group" "app" {
name = "${local.prefix}-app"
vpc_id = module.network.vpc_id
tags = local.common_tags
lifecycle {
create_before_destroy = true
}
}
resource "aws_security_group" "db" {
name = "${local.prefix}-db"
vpc_id = module.network.vpc_id
tags = local.common_tags
lifecycle {
create_before_destroy = true
}
}
# The rules are created AFTERWARDS, and each depends on both groups,
# but the groups do not depend on the rules. The graph is a tree.
resource "aws_vpc_security_group_egress_rule" "app_to_db" {
security_group_id = aws_security_group.app.id
referenced_security_group_id = aws_security_group.db.id
from_port = 5432
to_port = 5432
ip_protocol = "tcp"
}
resource "aws_vpc_security_group_ingress_rule" "db_from_app" {
security_group_id = aws_security_group.db.id
referenced_security_group_id = aws_security_group.app.id
from_port = 5432
to_port = 5432
ip_protocol = "tcp"
}The three families of cycle and how each one is broken:
| Family | Example | How to break it |
|---|---|---|
| Mutual reference between resources | Two security groups | Extract the relationship into a separate resource (rules, associations, attachments) |
Unnecessary depends_on |
depends_on = [module.app] on a module that app already depends on |
Remove it. An explicit depends_on on a whole module is the most frequent cause of artificial cycles |
| Cycle through a module | module.a uses an output of module.b and vice versa |
Split one of the two modules, or move the shared resource up a level |
When the cycle goes through a module the message becomes cryptic, because the addresses are long and you cannot take them in at a glance. The tool for seeing it is terraform graph, and reading it is covered in 09-02 §8. The quick trick:
# Filter the graph down to just the addresses in the error message.
terraform graph | grep -E "security_group|module\.data" | head -40A warning about
depends_onin modules. Every time you adddepends_onto amoduleblock, you are saying that all of that module depends on all of what you list. If that module returns an output the other one needs, you have closed the loop. The rule of thumb:depends_onon amoduleis the last resort, not the first, and it can almost always be replaced by passing the real value in as an input variable.
- The unknown-values error in the plan
This is the section that 06-02, 06-03 and 06-05 left pending. It is Terraform's conceptually deepest error, the one most people "solve" with a workaround that works once, and the only one that requires understanding the execution model in order to handle it properly.
7.1. The two messages
With count:
╷ │ Error: Invalid count argument │ │ on infra/app/certificates.tf line 42, in resource "aws_route53_record" "validation": │ 42: count = length(aws_acm_certificate.main.domain_validation_options) │ │ The "count" value depends on resource attributes that cannot be determined until │ apply, so Terraform cannot predict how many instances will be created. To work │ around this, use the -target argument to first apply only the resources that the │ count depends on. ╵
With for_each:
╷
│ Error: Invalid for_each argument
│
│ on infra/app/certificates.tf line 48, in resource "aws_route53_record" "validation":
│ 48: for_each = { for o in aws_acm_certificate.main.domain_validation_options :
│ 49: o.domain_name => o }
│ ├────────────────
│ │ aws_acm_certificate.main.domain_validation_options is a set of object,
│ │ known only after apply
│
│ The "for_each" map includes keys derived from resource attributes that cannot be
│ determined until apply, and so Terraform cannot determine the full set of keys
│ that will identify the instances of this resource.
│
│ When working with unknown values in for_each, it's better to define the map keys
│ statically in your configuration and place apply-time results only in the map
│ values.
│
│ Alternatively, you could use the -target planning option to first apply only the
│ resources that the for_each value depends on, and then apply a second time to
│ fully converge.
╵7.2. Why it really happens
Terraform separates plan and apply strictly, and that separation is what makes it possible for a human to review the plan and for the pipeline in 08-01 to apply exactly what was approved. For the plan to be reviewable, it has to enumerate every action. And to enumerate them, it has to know how many instances of each resource there will be.
A (known after apply) value is precisely a value that does not exist until the API is called. It is perfectly valid inside an argument — the plan will say subnet_id = (known after apply) and it will resolve at apply time — but not as a number of instances, because then the plan could not even say how many resources it is going to create.
flowchart TD
A["Is the value known at plan time?"] --> B{"Where does it come from?"}
B -->|"A literal, a variable,<br/>a local built from variables"| C["KNOWN<br/>Valid for count/for_each"]
B -->|"A data source"| D{"Are its arguments<br/>known?"}
D -->|Yes| C
D -->|"No (they depend on<br/>a new resource)"| E["UNKNOWN"]
B -->|"An attribute of a resource<br/>that ALREADY EXISTS in state"| C
B -->|"An attribute of a resource<br/>about to be created"| E
E --> F["Valid as an ARGUMENT<br/>(known after apply)"]
E --> G["NOT valid as<br/>count / for_each / keys"]
style C fill:#dcfce7,stroke:#15803d
style E fill:#fef3c7,stroke:#b45309
style G fill:#fee2e2,stroke:#b91c1c
The nuance that explains "well, it works for me". An attribute of a resource that already exists in state is known at plan time: Terraform read it during the refresh. That is why this error appears on the first apply of a brand-new environment and not on subsequent ones. That is the trap: the code passes CI in staging — where the certificate already existed — and blows up when creating prod from scratch. If your pipeline never deploys an environment from scratch, this error has been waiting for you for months.
7.3. The four strategies
| # | Strategy | When | Cost | Permanent |
|---|---|---|---|---|
| 1 | Known keys, unknown values | Almost always, and it is the right one | Rewriting the expression | Yes |
| 2 | -target in two passes |
An emergency, a first creation | Manual, cannot safely be automated | No |
| 3 | Split into two applies (two states) | The dependency is structural and stable | One more state, more orchestration | Yes |
| 4 | Restructure the data | When the shape of the data is the problem | A redesign | Yes |
Strategy 1: static keys, dynamic values. This is what the message itself suggests and what solves 80% of cases. Terraform needs to know the keys; the values can be unknown with no problem at all.
# WRONG: the key comes from an attribute that does not exist yet.
resource "aws_route53_record" "validation" {
for_each = {
for o in aws_acm_certificate.main.domain_validation_options :
o.domain_name => o
}
# ...
}# RIGHT: the key comes from var.domains, which is ALWAYS known.
# The value is looked up inside the unknown attribute, and that is allowed.
locals {
certificate_domains = toset([
"ecomarket.example.com",
"www.ecomarket.example.com",
"api.ecomarket.example.com",
])
}
resource "aws_acm_certificate" "main" {
domain_name = local.certificate_domains[0]
subject_alternative_names = slice(tolist(local.certificate_domains), 1, 3)
validation_method = "DNS"
tags = local.common_tags
lifecycle {
create_before_destroy = true
}
}
resource "aws_route53_record" "validation" {
# The key is a literal from the code: known at plan time.
for_each = local.certificate_domains
# The value is unknown, and that is perfectly legal.
name = one([
for o in aws_acm_certificate.main.domain_validation_options :
o.resource_record_name if o.domain_name == each.value
])
type = one([
for o in aws_acm_certificate.main.domain_validation_options :
o.resource_record_type if o.domain_name == each.value
])
records = [one([
for o in aws_acm_certificate.main.domain_validation_options :
o.resource_record_value if o.domain_name == each.value
])]
zone_id = data.aws_route53_zone.main.zone_id
ttl = 60
allow_overwrite = true
}What makes this work, line by line:
for_each = local.certificate_domains— asetbuilt from literals. At plan time Terraform knows there will be exactly three records, and their keys areecomarket.example.com,www...andapi....- The plan will show three resources to create, with
name,typeandrecordsmarked(known after apply). That is correct and reviewable. one([ for ... if ... ])looks inside the unknown attribute for the element matchingeach.value. During the plan the whole set is unknown, so the result is too; during apply it resolves.one()returns the single element of a one-element list, or fails if there are more — a free assertion.
Strategy 2: -target in two passes. The message itself suggests it, and it is worth being clear about what it is: a manual patch, not a solution.
# Step 1: create only the certificate.
terraform apply -target=aws_acm_certificate.main
# Step 2: domain_validation_options now exists in state and is known.
terraform applyWhat you lose with -target |
Why it matters |
|---|---|
| The plan no longer describes the full configuration | Terraform warns you: Note: You didn't use the -out option... and Resource targeting is in effect |
| It cannot safely be automated | A pipeline using -target is applying part of the system without reviewing the rest |
| It hides the problem | The code is still wrong; it only deploys correctly if somebody remembers the order |
At EcoMarket, -target in prod requires explicit approval and must be recorded in the PR, exactly like a force-unlock. The rule is that -target may get you out of a tight spot, but the PR that made it necessary is not closed until the code works without it.
Strategy 3: split into two applies. When the dependency is structural — the certificate and the DNS zone live in a different lifecycle from the load balancer — the answer is not an expression workaround, it is a state boundary. It is exactly the layered architecture of 07-01:
infra/ ├── 01-network/ # VPC, subnets, DNS zone ├── 02-data/ # RDS, S3, certificates └── 03-app/ # ALB, ECS, DNS records that consume the certificate
03-app reads the certificate ARN with data "terraform_remote_state", and at the time 03-app is planned that certificate already exists: its ARN is a known value. The error disappears by construction, with no trick at all.
Strategy 4: restructure the data. Sometimes the problem is not one of order but of shape. A real EcoMarket case: the network module returned a list of subnets and app did a for_each over it to create one endpoint per subnet.
# The module returned this, and the whole list was unknown
# on the first creation:
output "private_subnets" {
value = aws_subnet.private[*].id
}# Restructured: a map whose KEYS come from the input variable
# (known) and whose VALUES are the IDs (unknown).
output "private_subnets_by_az" {
value = {
for az, s in aws_subnet.private : az => s.id
}
}With the map, the consumer writes for_each = module.network.private_subnets_by_az and Terraform knows the keys because the output's for iterates over aws_subnet.private, whose instances come from var.availability_zones. The shape of the data went from "a list of unknown things" to "a map with known keys", and that is exactly what the error message asks for.
A mnemonic. You supply the keys; the cloud supplies the values. Every time you see
Invalid for_each argument, ask yourself: where does this key come from? If the answer contains the word "resource", you have your rewrite.
- Permission errors: the
AccessDenied that tells you nothing
AccessDenied that tells you nothingThis section pays off the debt from 07-04, where we warned that SCPs "break deployments in a way that is hard to diagnose: the error whoever debugs it will see is a generic AccessDenied, with no hint at all that the cause is an organisational policy two levels above your account".
8.1. The error that does help you
╷
│ Error: creating S3 Bucket (ecomarket-prod-images-noble-bee): operation error S3:
│ CreateBucket, https response error StatusCode: 403, RequestID:
│ 7QZ4M2K1N8P3Q5R7, HostID: k2Nv..., api error AccessDenied: User:
│ arn:aws:sts::123456789014:assumed-role/ecomarket-terraform-prod/github-actions-ecomarket-infra-4821
│ is not authorized to perform: s3:CreateBucket on resource:
│ "arn:aws:s3:::ecomarket-prod-images-noble-bee" with an explicit deny in a
│ service control policy
│
│ with aws_s3_bucket.images,
│ on infra/data/datastore.tf line 12, in resource "aws_s3_bucket" "images":
│ 12: resource "aws_s3_bucket" "images" {
│
╵This message is a gift and you need to learn to recognise it. It contains five pieces of data that close the diagnosis without your opening a single console:
| Data point | Value in the example | What it tells you |
|---|---|---|
| The effective identity | assumed-role/ecomarket-terraform-prod/github-actions-...-4821 |
The role that was assumed and the session name. Confirms that the OIDC of 08-03 worked and that this is not a wrong-identity problem |
| The action | s3:CreateBucket |
The exact string to search for in the policies |
| The resource | arn:aws:s3:::ecomarket-prod-images-noble-bee |
What it was denied on |
| The reason | with an explicit deny in a service control policy |
The root cause, handed to you on a plate |
The RequestID |
7QZ4M2K1N8P3Q5R7 |
What AWS support will ask for |
The phrase with an explicit deny in a service control policy means that no permission is missing: there is an explicit denial, and a denial in an SCP cannot be compensated for by adding permissions to the role. However much AdministratorAccess you give it, it will keep failing. The fix belongs to the organisational unit, not the account.
The variants of that closing phrase and what they translate to:
| Closing phrase of the message | What it means | Where it gets fixed |
|---|---|---|
| (none) | The permission is simply missing from the role's policy | In the account's role |
with an explicit deny in a service control policy |
An organisation SCP forbids it | In the organisational unit's SCP |
with an explicit deny in a resource-based policy |
The resource's policy (bucket, KMS, queue) forbids it | On the resource, which may live in another account |
with an explicit deny in an identity-based policy |
There is a Deny in the role's own policy |
In the role |
with an explicit deny in a permissions boundary |
The permissions boundary trims what the role can do | In the permissions boundary |
because no identity-based policy allows the ... action |
There is no Allow, and no Deny either |
In the role |
because no VPC endpoint policy allows the ... action |
The VPC endpoint policy is blocking it | On the endpoint |
8.2. The generic error, which is the real problem
Not every AWS service returns the long message. Many — and all the ones using the old S3 API, or calls that fail before the full policy is evaluated — return this:
╷ │ Error: reading S3 Bucket (ecomarket-tfstate): operation error S3: HeadBucket, │ https response error StatusCode: 403, RequestID: D8J2K4L6M8N0P2Q4, HostID: ..., │ api error Forbidden: Forbidden ╵
Or, in the worst case:
Zero information. It does not say which identity, it does not say which action, it does not say why. And this is the error you need to know how to diagnose, because it is the one that shows up at three in the morning.
8.3. The diagnostic procedure, in order
flowchart TD
A["AccessDenied with no detail"] --> B["1. Which identity am I?<br/>aws sts get-caller-identity"]
B --> C{"Is it the identity<br/>I expected?"}
C -->|No| D["Wrong credentials:<br/>profile, environment variables,<br/>role not assumed → solved"]
C -->|Yes| E["2. Which exact action failed?<br/>TF_LOG=DEBUG → 09-02<br/>or CloudTrail by RequestID"]
E --> F["3. Simulate the policy<br/>iam simulate-principal-policy"]
F --> G{"Does the simulation<br/>say allowed?"}
G -->|"denied,<br/>implicitDeny"| H["An Allow is missing<br/>→ widen the role"]
G -->|"denied,<br/>explicitDeny"| I["4. Where does the Deny come from?"]
G -->|allowed| J["The role's policy allows it,<br/>but something above does not:<br/>SCP, boundary, resource policy"]
I --> K["CloudTrail:<br/>errorCode + errorMessage<br/>of the real event"]
J --> K
K --> L["5. describe-organization<br/>list-policies-for-target<br/>for every level of the OU"]
L --> M["Talk to the team<br/>that manages the organisation"]
style D fill:#dcfce7,stroke:#15803d
style H fill:#dcfce7,stroke:#15803d
style M fill:#fef3c7,stroke:#b45309
Step 1: confirm the identity. It is the step everybody skips and the one that solves a third of the cases.
{
"UserId": "AROAX3EXAMPLE:github-actions-ecomarket-infra-4821",
"Account": "123456789014",
"Arn": "arn:aws:sts::123456789014:assumed-role/ecomarket-terraform-prod/github-actions-ecomarket-infra-4821"
}Two immediate checks: is the account the one you expected (...14 is prod), and is the role ecomarket-terraform-prod rather than ecomarket-terraform-plan-prod? The second case is the most common of all: the apply job ran with the read-only role, because somebody copied a step from one workflow into another. It is exactly the scenario the account checks of 06-05 protect against:
# infra/app/guards.tf — the guard that turns an incomprehensible
# AccessDenied into a message that says what is going on.
data "aws_caller_identity" "current" {}
check "correct_account" {
assert {
condition = data.aws_caller_identity.current.account_id == {
dev = "123456789012"
staging = "123456789013"
prod = "123456789014"
}[var.environment]
error_message = format(
"You are pointing at account %s with environment=%s. Check the assumed role and the -var-file. Contact: [email protected]",
data.aws_caller_identity.current.account_id,
var.environment
)
}
}Step 2: find out the exact action. If the error does not say, there are two routes. The first is TF_LOG=DEBUG, filtering for the HTTP request (09-02 §4). The second is CloudTrail, which is usually faster because CloudTrail's errorMessage is often more explicit than the one that reaches the client:
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=CreateBucket \
--start-time "$(date -u -d '30 minutes ago' +%Y-%m-%dT%H:%M:%SZ)" \
--max-results 10 \
--query 'Events[].CloudTrailEvent' --output text \
| jq -r 'select(.errorCode != null)
| {time: .eventTime, error: .errorCode, message: .errorMessage,
who: .userIdentity.arn, action: .eventName}'What each part does:
lookup-eventssearches for events by operation name over the last 30 minutes.--query 'Events[].CloudTrailEvent'extracts the raw event, which is a JSON string inside the JSON.jq 'select(.errorCode != null)'keeps only the ones that failed.- The final projection leaves five readable fields instead of an 80-line event.
Step 3: simulate the policy. It answers "is this a problem with the role or with something above it?":
aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::123456789014:role/ecomarket-terraform-prod \
--action-names s3:CreateBucket \
--resource-arns "arn:aws:s3:::ecomarket-prod-images-noble-bee" \
--query 'EvaluationResults[].{action:EvalActionName,decision:EvalDecision,source:MatchedStatements[].SourcePolicyId}'[
{
"action": "s3:CreateBucket",
"decision": "allowed",
"source": ["ecomarket-terraform-prod-policy"]
}
]And here is the heart of the matter. The simulation says allowed and the real apply fails. That contradiction is not a bug: simulate-principal-policy evaluates the account's identity policies and does not evaluate the organisation's SCPs. When the simulation says allowed and reality says AccessDenied, the cause is outside the account, and you have just eliminated the entire search space inside it in one go.
Steps 4 and 5: climb the hierarchy. With read permissions on the organisation:
# Which organisational unit is this account in?
aws organizations list-parents --child-id 123456789014
# Which policies apply at that level? And you have to repeat it all the way
# up to the root: an SCP is inherited by every level below it.
aws organizations list-policies-for-target \
--target-id ou-a1b2-c3d4e5f6 \
--filter SERVICE_CONTROL_POLICY
# And read the one you suspect:
aws organizations describe-policy --policy-id p-a1b2c3d4 \
--query 'Policy.Content' --output text | jq .{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyBucketsWithoutMandatoryEncryption",
"Effect": "Deny",
"Action": "s3:CreateBucket",
"Resource": "*",
"Condition": {
"Null": {
"s3:x-amz-server-side-encryption": "true"
}
}
}
]
}There is the cause, and it has nothing to do with the role: the organisation forbids creating buckets without specifying encryption in the call itself. The fix is not to touch IAM, it is to have the resource specify it.
If you do not have read permissions on the organisation — the normal situation in a product team — the diagnosis ends here and the correct action is to open a ticket with the security team containing: the RequestID, the identity's ARN, the exact action, the resource, and the output of simulate-principal-policy saying allowed. With those five data points, the security team locates the SCP in two minutes. Without them, the conversation lasts two days.
8.4. The same problem in Azure and GCP
| Platform | Typical message | The "two levels up" mechanism | Where to look |
|---|---|---|---|
| AWS | AccessDenied ... with an explicit deny in a service control policy |
SCP on the OU, permissions boundary, resource policy | organizations list-policies-for-target, iam simulate-principal-policy, CloudTrail |
| Azure | AuthorizationFailed: The client '...' with object id '...' does not have authorization to perform action '...' over scope '...' |
Azure Policy with a Deny effect on the subscription or the management group; resource locks (CannotDelete, ReadOnly) |
az policy state list --filter "complianceState eq 'NonCompliant'", az lock list, the activity log |
| GCP | Error 403: Permission 'compute.networks.create' denied on resource ..., forbidden |
Organisation policy constraints (constraints/compute.vmExternalIpAccess, constraints/iam.disableServiceAccountKeyCreation), VPC Service Controls |
gcloud resource-manager org-policies list --organization=..., the audit logs, gcloud policy-troubleshoot iam |
The structure of the diagnosis is identical on all three: identity → action → account policy → hierarchy policy. The only thing that changes is the commands.
The Azure-specific detail that costs the most is the resource lock: a CannotDelete on a resource group makes destroy fail with an AuthorizationFailed that looks like a permissions problem and is not one. az lock list --resource-group ecomarket-prod settles it in one command.
The GCP-specific detail is VPC Service Controls: they produce 403 errors on operations that IAM permits perfectly well, with a message that includes violationsCount and a unique violation identifier. That identifier is what you take to the security team.
- Provider API errors
You are no longer debugging Terraform: you are debugging the cloud. The diagnosis moves elsewhere.
9.1. What Terraform retries on its own
This table saves a lot of time, because it stops you "fixing" things that fix themselves:
| Situation | Retried? | Detail |
|---|---|---|
Transient network error, 5xx |
Yes, by the provider's SDK | Retry with exponential backoff, up to ~25 attempts in the AWS provider |
Rate limit (Throttling, RequestLimitExceeded) |
Yes | Same mechanism. If it still fails, the limit really is saturated |
| Eventual consistency on reads | Partially | Many resources have specific waits coded into the provider |
AccessDenied |
No | It is deterministic: retrying changes nothing |
Quota exceeded (LimitExceeded) |
No | Requires human action |
Name conflict (AlreadyExists) |
No | Requires a decision: import or rename |
| State-wait timeout | No | The timeout was the retry |
The practical consequence: if you see exceeded maximum number of attempts, 25 in the message, the provider already retried 25 times. Relaunching the apply is unlikely to help; the problem is structural.
9.2. AlreadyExists: the resource is already there
╷
│ Error: creating IAM Role (ecomarket-prod-app-tasks): operation error IAM: CreateRole,
│ https response error StatusCode: 409, RequestID: 6f2a91d0-b3e8-4c0e-9b77-4d318e5c,
│ EntityAlreadyExists: Role with name ecomarket-prod-app-tasks already exists.
│
│ with aws_iam_role.app_tasks,
│ on infra/app/compute.tf line 96, in resource "aws_iam_role" "app_tasks":
│ 96: resource "aws_iam_role" "app_tasks" {
│
╵What it really means. Terraform tried to create the resource because it is not in its state. But it exists in the cloud. The causes, in order of frequency, and each one calls for a different action:
| Cause | How to confirm it | Action |
|---|---|---|
An earlier apply created it and died before saving the state |
The failed apply's log, and CloudTrail | Import it (06-04) |
| Somebody created it by hand | CloudTrail: who and when | Import it, or delete it and let Terraform create it |
| Another state manages it | Search for the name in the other states | Stop. This is the overlapping-states case of 09-03 |
| A genuine name collision between environments | Does the name include local.prefix? |
Fix the name. Globally unique names need a random suffix |
# Does any of my states already know about it? A check before importing.
for component in network data app; do
echo "--- ${component} ---"
terraform -chdir="infra/${component}" state list 2>/dev/null \
| grep -i "app_tasks" || true
doneImportant warning. Importing a resource that another state already manages produces no error at all: both states will believe they own it and each
applywill undo what the other did. It is the worst state-management scenario and it is covered in 09-03. That is why the check above goes before theimport, not after.
9.3. Rate limiting
╷ │ Error: reading EC2 Security Group Rules: operation error EC2: │ DescribeSecurityGroupRules, exceeded maximum number of attempts, 25, https response │ error StatusCode: 503, RequestID: 8c3d1e2f-4a5b-6c7d-8e9f-0a1b2c3d4e5f, api error │ RequestLimitExceeded: Request limit exceeded. ╵
What it actually says: the provider retried 25 times and kept getting 503. This is not a one-off glitch; EcoMarket's state is asking for more than the API tolerates.
The two causes and their fixes:
# Cause A: too much parallelism. Terraform uses 10 simultaneous operations
# by default; with a 400-resource state, the refresh saturates the API.
terraform plan -parallelism=5
# Cause B: too many resources in one state. This is the real fix,
# and it is the layered architecture of 07-01.| Lever | Effect | Cost |
|---|---|---|
-parallelism=5 |
Fewer requests per second | The plan takes twice as long |
-refresh=false on PR plans |
Removes the full refresh | The plan may not see drift. Only acceptable for informational plans |
| Splitting the state by component | Each apply refreshes a subset |
It is architectural work, and it is the right answer |
| Raising the limit with the cloud provider | More quota | Only some services, and you have to ask |
The number to watch at EcoMarket: if a plan in prod takes more than five minutes just refreshing, the state is too big. That is the signal that it is time to split it, and it is better acted on before the API starts rejecting requests.
9.4. Eventual consistency
╷ │ Error: creating ELBv2 Listener: operation error Elastic Load Balancing v2: │ CreateListener, https response error StatusCode: 400, RequestID: ..., │ CertificateNotFound: Certificate 'arn:aws:acm:eu-west-1:123456789014:certificate/ │ 3f8a2b1c-...' not found ╵
And the certificate does exist. You have just created it in this very apply, you can see it in the console, and the listener says it does not exist. This is eventual consistency: the resource was created in one control plane and the service that consumes it cannot see it yet.
Three signals that identify an eventual-consistency problem:
- The resource mentioned does exist if you query it with the provider's CLI.
- Relaunching the
applywithout changing anything works. - It fails intermittently, not always.
The correct fix is not a sleep, even though it is the first thing everybody writes:
# WRONG: a fixed sleep. It works until the day the cloud is slow,
# and it makes every apply thirty seconds longer, for ever.
resource "time_sleep" "wait_for_certificate" {
depends_on = [aws_acm_certificate.main]
create_duration = "30s"
}# RIGHT: wait for the CONDITION, not for the clock. The ACM validation
# resource exists precisely for this: it does not finish until the
# certificate is issued and usable.
resource "aws_acm_certificate_validation" "main" {
certificate_arn = aws_acm_certificate.main.arn
validation_record_fqdns = [for r in aws_route53_record.validation : r.fqdn]
timeouts {
create = "10m"
}
}
resource "aws_lb_listener" "https" {
load_balancer_arn = aws_lb.main.arn
port = 443
protocol = "HTTPS"
# Depend on the VALIDATION, not on the certificate. This is the line
# that removes the error, and it is a single one.
certificate_arn = aws_acm_certificate_validation.main.certificate_arn
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.app.arn
}
}The general rule: almost every provider has a resource or an attribute that waits, for the cases where eventual consistency matters. Look for _validation, _attachment, wait_for_ or a timeouts block before you write a sleep.
9.5. Timeouts
╷
│ Error: waiting for RDS DB Instance (ecomarket-prod-db-noble-bee) create: timeout
│ while waiting for state to become 'available' (last state: 'creating', timeout:
│ 40m0s)
│
│ with aws_db_instance.main,
│ on infra/data/datastore.tf line 30, in resource "aws_db_instance" "main":
│ 30: resource "aws_db_instance" "main" {
│
╵This is the most dangerous error in this section, and the reason is the word waiting. The resource was created. AWS is building it right now. Terraform got tired of waiting.
What happens in the state — and it is important to get this right: the AWS provider usually records the resource with the attributes it knows, but it may be left marked as tainted, or with incomplete attributes. What you must never do is assume it does not exist.
# 1. Does Terraform have it? In what shape?
terraform state list | grep aws_db_instance
terraform state show aws_db_instance.main | head -20
# 2. Does it really exist in AWS, and in what state?
aws rds describe-db-instances \
--db-instance-identifier ecomarket-prod-db-noble-bee \
--query 'DBInstances[0].{status:DBInstanceStatus,created:InstanceCreateTime}'
# 3. If it is "available", wait and relaunch the apply: the refresh
# will fill in the missing attributes.
# 4. If the state does NOT have it and AWS does: orphaned resource → 09-03.Raising the timeout is legitimate when you know that resource takes longer:
resource "aws_db_instance" "main" {
# ...
timeouts {
create = "90m" # A large Multi-AZ instance can exceed 40 min
update = "90m"
delete = "60m"
}
}But raising the timeout fixes nothing if the cause is something else: a restore from a large snapshot, a maintenance window, an exhausted IOPS quota. Before touching timeouts, look at the resource's events in the provider's console.
9.6. destroy errors
╷
│ Error: Instance cannot be destroyed
│
│ on infra/data/datastore.tf line 30:
│ 30: resource "aws_db_instance" "main" {
│
│ Resource aws_db_instance.main has lifecycle.prevent_destroy set, but the plan
│ calls for this resource to be destroyed. To avoid this error and continue with the
│ plan, either disable lifecycle.prevent_destroy or reduce the scope of the plan using
│ the -target option.
╵This is not an error: it is the guard working. The right question is not "how do I remove it" but "why does the plan want to destroy the production database". Almost always it is a replacement forced by an attribute change, not an intentional destruction, and the answer is in the plan JSON (09-02 §6):
terraform show -json plan.tfplan \
| jq -r '.resource_changes[]
| select(.change.actions | contains(["delete"]))
| "\(.address): \(.change.actions | join(",")) due to \(.change.replace_paths // "n/a")"'And the external-dependency error:
╷ │ Error: deleting EC2 Subnet (subnet-0a1b2c3d4e5f67890): operation error EC2: │ DeleteSubnet, https response error StatusCode: 400, RequestID: ..., api error │ DependencyViolation: The subnet 'subnet-0a1b2c3d4e5f67890' has dependencies and │ cannot be deleted. ╵
What it means: something lives in that subnet and Terraform does not know about it, because another system created it. At EcoMarket the usual suspects are Lambda-in-VPC network interfaces, endpoints created by a data team, or an instance launched by hand for debugging and never deleted.
# What is actually in the subnet:
aws ec2 describe-network-interfaces \
--filters "Name=subnet-id,Values=subnet-0a1b2c3d4e5f67890" \
--query 'NetworkInterfaces[].{id:NetworkInterfaceId,desc:Description,status:Status}' \
--output table
- Provider consistency errors
This section pays off the debt from 08-05, where the message Provider produced inconsistent final plan appeared with no explanation.
10.1. The two messages and the difference between them
╷ │ Error: Provider produced inconsistent final plan │ │ When expanding the plan for aws_s3_bucket_lifecycle_configuration.images to include │ new values learned so far during apply, provider "registry.terraform.io/hashicorp/aws" │ produced an invalid new value for .rule[0].filter: block count changed from 0 to 1. │ │ This is a bug in the provider, which should be reported in the provider's own issue │ tracker. ╵
╷ │ Error: Provider produced inconsistent result after apply │ │ When applying changes to aws_ecs_service.app, provider │ "registry.terraform.io/hashicorp/aws" produced an unexpected new value: │ .capacity_provider_strategy: block count changed from 1 to 0. │ │ This is a bug in the provider, which should be reported in the provider's own issue │ tracker. ╵
inconsistent final plan |
inconsistent result after apply |
|
|---|---|---|
| When it is detected | While refining the plan during apply, before calling the API | After calling the API |
| Was anything modified? | No. The apply aborts before writing | Yes. The resource was created or modified |
| State of the state | Unchanged for that resource | The resource stays in the state, possibly with divergent attributes |
| Severity | Annoying | Serious: you have to verify what was left behind |
The distinction matters a great deal in production: the first leaves you where you were; the second leaves you with a created resource whose recorded state may not describe it properly.
10.2. What they really mean
The message says This is a bug in the provider. That is formally true and practically misleading. What has happened is this:
- Terraform computed a plan: "this attribute will be X".
- The provider, when refining or applying, returned Y.
- Terraform checks that the promise was kept. It was not. It aborts.
That check exists to protect the contract that makes the plan reviewable: if the provider could promise one thing and do another, approving a plan would mean nothing.
The three real causes, by frequency:
| Cause | What happens | Distinguishing signal |
|---|---|---|
| The API normalises the value (≈50%) | You ask for "us-east-1" and the API stores "US-EAST-1"; you send JSON with whitespace and it comes back compacted; you send a CIDR 10.0.0.0/8 and it returns 10.0.0.0/8 with the rules in a different order |
The attribute mentioned is a formatted string: JSON, an ARN, policies, rule lists |
| A genuine provider bug (≈35%) | A new or little-used resource whose Read is badly implemented |
block count changed, and an open issue describing exactly the same thing |
Interaction with ignore_changes or default values (≈15%) |
An optional attribute the API fills in and the provider was not expecting | The attribute is not in your configuration |
10.3. How to confirm it
# 1. Which exact attribute? It is in the message: .rule[0].filter
# 2. What does the state say AFTER the attempt?
terraform state show aws_s3_bucket_lifecycle_configuration.images
# 3. What does the cloud ACTUALLY say?
aws s3api get-bucket-lifecycle-configuration \
--bucket ecomarket-prod-images-noble-bee | jq .
# 4. Is it reproducible with a minimal configuration? (step 5 of the method)
# This is what turns "something odd is happening to me" into a useful issue: 09-04.
# 5. Is there an open issue? Search for the STABLE part of the message:
# "inconsistent final plan" "aws_s3_bucket_lifecycle_configuration" filterSteps 3 and 5 are the ones that really decide it. If the cloud holds a different value from the one you asked for, it is normalisation. If there is an issue with your exact attribute, it is a known bug and there is probably already a version with the fix.
10.4. What to do in the meantime
Option A: pin the provider version. If it worked with the previous one, this is the immediate answer and the least invasive:
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
# Pinned because of the consistency failure in
# aws_s3_bucket_lifecycle_configuration with 5.63.0.
# Issue hashicorp/terraform-provider-aws#38402.
# Review at the October upgrade. — [email protected]
version = "= 5.62.0"
}
}
}The comment is not optional. A pinned version with no explanation is technical debt nobody dares touch; with an issue and a review date, it is a decision with an expiry. It is the update policy that gets settled in 09-04.
Option B: ignore_changes on the specific attribute. Only if the normalised value is functionally equivalent:
resource "aws_ecs_service" "app" {
# ...
lifecycle {
# The API fills in capacity_provider_strategy when the cluster has
# a default capacity provider. The value is equivalent to ours;
# the provider does not reconcile it properly.
ignore_changes = [capacity_provider_strategy]
}
}Warning.
ignore_changesis a mute button, not a fix. From that moment on Terraform stops managing that attribute and will not warn you if it really changes. Scope it to the exact attribute — neverignore_changes = all— document why, and revisit it when you upgrade the provider.
Option C: restructure to avoid the path. In the aws_s3_bucket_lifecycle_configuration case, declaring filter {} explicitly — the detail from §5.2 — makes the plan and the result agree, and the error disappears without muting anything.
Option D: report it. If you got to step 4 and you have a minimal reproduction, you have the most valuable thing you can give an open-source project. How to turn it into an issue that actually gets fixed is the subject of 09-04.
- Errors that cross module layers
11.1. The question: is this line mine?
╷ │ Error: Unsupported argument │ │ on .terraform/modules/platform/modules/data/main.tf line 84, in resource │ "aws_db_instance" "main": │ 84: manage_master_user_password = true │ │ An argument named "manage_master_user_password" is not expected here. ╵
The path answers the question, and there are four forms worth telling apart at a glance:
| The path starts with | It is code that is | Can you edit it | What to do |
|---|---|---|---|
infra/, modules/, or a loose .tf |
Yours | Yes | Fix it |
.terraform/modules/<name>/ |
A downloaded remote module | No (it is wiped on every init) |
Diagnose here, fix at the source or in the call |
../../modules/network/ |
A local module | Yes | Fix it |
.terragrunt-cache/xxxx/yyyy/ |
A copy generated by Terragrunt | No | Translate the path back to its origin (§11.3) |
In this particular case, the full diagnosis is: the ecomarket-platform module uses an argument that does exist in the AWS provider ≥ 5.30, but your lock file pins 5.20. The module is not broken and neither is your code; the combination is. The fix is not to touch either one, it is to raise the provider.
# Confirm the hypothesis in two commands:
terraform version # which aws version do I have?
grep -A5 required_providers .terraform/modules/platform/versions.tfIf the module declares >= 5.30 and your lock pins 5.20, you should have seen an init error (§4.2). If the module declares >= 5.0, the module has a bug: it uses a feature its own constraint does not guarantee. That is a perfectly reportable issue, and probably a one-line PR.
11.2. Reading the code that is actually running
# Which modules are downloaded and where did they come from?
jq -r '.Modules[] | select(.Key != "") | "\(.Key)\t\(.Source)\t\(.Dir)"' \
.terraform/modules/modules.json | column -tplatform git::ssh://[email protected]/ecomarket/terraform-aws-ecomarket-platform.git?ref=v3.4.0 .terraform/modules/platform platform.data ./modules/data .terraform/modules/platform/modules/data platform.network ./modules/network .terraform/modules/platform/modules/network vpc registry.terraform.io/terraform-aws-modules/vpc/aws .terraform/modules/vpc
Three things this output gives you and nothing else does:
- The exact version that was downloaded. Your
main.tfsays~> 3.0; this saysv3.4.0. When the error appeared "without anything changing", this line is usually the answer. - The correspondence between the error's path and the logical module.
.terraform/modules/platform/modules/dataismodule.platform.module.data, and that is the address you need forterraform consoleorterraform state. - What is remote and what is local. Paths beginning with
./are internal submodules of the remote module; only the first entry was actually downloaded.
# Read the real code, with context around the error's line:
sed -n '70,100p' .terraform/modules/platform/modules/data/main.tf
# And check whether the problem is already fixed upstream:
git -C /tmp ls-remote --tags \
ssh://[email protected]/ecomarket/terraform-aws-ecomarket-platform.git \
| tail -5Warning. Editing files inside
.terraform/modules/in order to "try something" is a legitimate quick diagnostic, but remember two things: the nextterraform initwipes it without warning, and if the module has a shared cache entry (TF_PLUGIN_CACHE_DIRdoes not affect modules, but a persistent runner can reuse the directory) you could be contaminating other runs. Try it, write down the result, and revert withterraform init -upgrade.
11.3. The Terragrunt trail
With Terragrunt, the error's path points somewhere that does not exist in your repository, because Terragrunt does not run Terraform in your directory: it copies the module and the generated files into .terragrunt-cache/ and runs there (07-05).
╷
│ Error: Invalid value for input variable
│
│ on /home/runner/work/ecomarket-infra/ecomarket-infra/live/prod/data/
│ .terragrunt-cache/xK9mP2nQ8vR4/tY7wL1zB3cF6/main.tf line 14:
│ 14: variable "backup_retention" {
│
│ The given value is not suitable for var.backup_retention declared at main.tf:14,1-28:
│ a number is required.
╵How that path translates:
live/prod/data/ ← your terragrunt.hcl: the cause is HERE
.terragrunt-cache/
xK9mP2nQ8vR4/ ← hash of the module's URL
tY7wL1zB3cF6/ ← hash of the specific version
main.tf ← the copied module (somebody else's code)The rule: the prefix before .terragrunt-cache is your Terragrunt unit, and that is where the terragrunt.hcl defining the inputs lives. The part after it is module code. In this example, main.tf:14 declares the variable; the wrong value is supplied by your terragrunt.hcl:
# The REAL inputs after resolving every include and locals:
terragrunt render-json --terragrunt-json-out /tmp/resolved.json
jq '.inputs.backup_retention' /tmp/resolved.jsonThere it is: a string "30" where the variable expects a number. And it is not in your live/prod/data/ terragrunt.hcl but in an include coming from live/prod/environment.hcl, where somebody wrote backup_retention = "30" with quotes. render-json is the tool that makes the composition visible, and without it the diagnosis is guesswork.
The three diagnostic techniques with Terragrunt, in order of use:
# 1. Which inputs actually reach the module?
terragrunt render-json --terragrunt-json-out /tmp/resolved.json && jq . /tmp/resolved.json
# 2. Which files has Terragrunt generated? (backend, provider, versions)
find .terragrunt-cache -name "*.tf" -newer terragrunt.hcl -exec sh -c \
'echo "=== $1 ==="; cat "$1"' _ {} \;
# 3. Drop down to plain Terraform: run INSIDE the cache.
# If it fails here too, the problem is Terraform's, not Terragrunt's.
cd .terragrunt-cache/*/*/ && terraform planTechnique 3 is the one that separates "this is a Terragrunt problem" from "this is a problem with my Terraform" fastest, and it is the one 07-05 announced would be detailed here.
- Errors that only happen in CI
The closing of module 8 described the scenario: "an ephemeral runner, with no TTY, no colours, none of your AWS profile, none of your provider cache and none of your shell history". Each of those absences produces a family of errors.
| Difference | Typical symptom | Diagnosis | Fix |
|---|---|---|---|
| No TTY | The job hangs until the timeout with no message | The last log line is var.db_password\n Enter a value: |
-input=false and TF_INPUT=false (08-01 §2) |
| No colour | grep/jq over the output find nothing |
cat -v output.txt shows ^[[32m |
-no-color, always, in CI |
| A different Terraform version | Call to unknown function, or Unsupported block type on something valid |
terraform version in both places |
Pin the version in the workflow and in required_version |
| A different provider version | Unsupported argument on something documented |
terraform providers schema -json |
Lock file under version control + -lockfile=readonly |
| Different credentials | AccessDenied in CI but not locally |
aws sts get-caller-identity in both |
The plan role is not the apply role (§8.3) |
| Cold cache | init takes 4 minutes, or fails on a Registry rate limit |
Compare durations between runs | TF_PLUGIN_CACHE_DIR + the runner's cache |
| Lock file without the runner's platform | doesn't match any of the checksums |
The lock file only has darwin_arm64 |
terraform providers lock -platform=linux_amd64 (§4.3) |
| Clock out of sync | SignatureDoesNotMatch, or the OIDC token rejected |
date -u on the runner |
Sync NTP; in containers, the host's clock |
| Non-persistent working directory | Backend configuration changed, or an empty .terraform/ |
The other job's init never arrived |
Pass .terraform/ and the plan through as artefacts (08-01 §6) |
| Environment variables inherited locally | It works on your machine "with nothing configured" | env | grep -i '^TF_|^AWS_' |
Reproduce the runner's environment (09-02 §11) |
12.1. The three most expensive, with their message
Clock out of sync. The most bewildering of the lot, because the message talks about signatures and the cause is the time of day:
╷ │ Error: reading S3 Bucket (ecomarket-tfstate): operation error S3: HeadBucket, │ https response error StatusCode: 403, api error SignatureDoesNotMatch: The request │ signature we calculated does not match the signature you provided. Check your key and │ signing method. ╵
AWS signatures include a timestamp and are only valid within a window of a few minutes. A runner whose clock is five minutes fast produces signatures AWS rejects. The same symptom takes down the OIDC of 08-03, because the JWT has iat and exp. Diagnosis: date -u on the runner compared with curl -sI https://s3.eu-west-1.amazonaws.com | grep -i ^date.
An inherited environment variable. The most frustrating "it works on my machine" case:
# On your laptop this has been in your .bashrc for months:
export TF_VAR_db_password="..."
export AWS_PROFILE="ecomarket-prod"
# On the runner it does not exist, and the error is:╷
│ Error: No value for required variable
│
│ on variables.tf line 48:
│ 48: variable "db_password" {
│
│ The root module input variable "db_password" is not set, and has no default value. Use
│ a -var or -var-file command line argument to provide a value for this variable.
╵The diagnosis is one command and it deserves a place in CONTRIBUTING.md:
# What your shell is handing Terraform without your knowing:
env | grep -E '^(TF_|AWS_|ARM_|GOOGLE_)' | sed 's/=.*/=<hidden>/'That final sed is not paranoia: TF_VAR_db_password is a secret and this output ends up pasted into a chat.
Concurrency between jobs. The error is the locking one from 03-04, but its cause here is pipeline configuration:
╷ │ Error: Error acquiring the state lock │ │ Error message: operation error DynamoDB: PutItem, https response error StatusCode: │ 400, ConditionalCheckFailedException: The conditional request failed │ Lock Info: │ ID: a3f1c9d2-7b84-4e60-9c15-2d8f6a0b3e47 │ Path: ecomarket-tfstate/ecomarket/prod/app/terraform.tfstate │ Operation: OperationTypeApply │ Who: runner@fv-az1234-567 │ Version: 1.9.5 │ Created: 2026-09-23 08:14:22.481293 +0000 UTC │ │ Terraform acquires a state lock to protect the state from being written by multiple │ users at the same time. Please resolve this issue above and try again. ╵
How to read this information block, because each field decides a different thing:
Pathconfirms which state we are talking about:ecomarket/prod/app/terraform.tfstate. If you were expectingstaging, the problem is not the lock, it is that you are in the wrong environment.Who: runner@fv-az1234-567is an ephemeral GitHub Actions runner that no longer exists. That is the signature of an orphaned lock.Createdagainst the current time: less than fifteen minutes, there is probably a live apply; hours, it is almost certainly orphaned.Operation: OperationTypeApplyis the serious data point: if it wereOperationTypePlan, forcing is almost harmless; beingApply, there may be a half-finished apply.Version: 1.9.5tells you which version took it. If it does not match yours, there are two different CI configurations pointing at the same state.
The full procedure — the checklist before force-unlock and what to review afterwards — belongs to 09-03. Here it is enough to recognise the message and to know that the prevention lies in the concurrency group of 08-01 §11.
12.2. The golden rule for CI errors
If an error appears in CI and not locally, do not look in the code: look at the differences. And for that search to be quick, the pipeline has to print them. Add a diagnostics block at the start of every job that costs two seconds and saves hours:
# ci/diagnostic.sh — runs at the start of every Terraform job.
set -euo pipefail
echo "::group::Environment diagnostics"
echo "Runner UTC date : $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "Terraform : $(terraform version -json | jq -r .terraform_version)"
echo "Platform : $(uname -sm)"
echo "Directory : $(pwd)"
echo "Target environment : ${ENVIRONMENT}"
echo "--- Effective identity ---"
aws sts get-caller-identity --output json | jq '{account: .Account, arn: .Arn}'
echo "--- Terraform variables present (no values) ---"
env | grep -E '^(TF_|AWS_)' | sed 's/=.*/=<present>/' | sort
echo "--- Locked providers ---"
grep -E '^provider|^ version' .terraform.lock.hcl | paste - -
echo "::endgroup::"Five sections, each answering one question from the table above: clock, version, platform, identity, environment, providers. When somebody pastes a CI failure into the team channel, this block is the first thing anybody asks for, and having it already printed turns a twenty-message conversation into a two-message one.
Common Mistakes and Tips
Reading only the first line of the error. That is the category, not the cause. The detail is underneath, and it often includes the exact suggestion or the command that settles the diagnosis (terraform providers, terraform init -upgrade). Tip: read the whole thing, every time, even when you think you already know what is going on. It costs ten seconds.
Believing the error's line is where the problem is. The on <file> line <N> reference says where it was detected. The cause may be in a .tfvars, in a downloaded module, in a provider version or in an organisational policy. Tip: for every error, ask yourself explicitly "is this line the cause or the symptom?".
Ignoring Warning:s. A warning is a future error with a delivery date. Value for undeclared variable means a production value is being ignored silently. Tip: count the warnings in the pipeline and publish them in the PR headline; and treat Value for undeclared variable as an error, because it almost always is one.
Putting -target in the pipeline. The Invalid count argument message suggests it, which is why it ends up in a workflow. A pipeline with -target applies part of the system without reviewing the rest, and hides a design problem in the code. Tip: -target is an interactive emergency tool; if the code needs it to deploy from scratch, the code is wrong (§7.3).
Solving eventual consistency with sleep. It works until the cloud is slow, and from then on every apply takes thirty seconds longer, for ever. Tip: look for the provider's waiting resource (_validation, _attachment, timeouts); wait for the condition, not for the clock.
Treating This is a bug in the provider as a verdict. Half the time it is an API normalisation that is resolved by declaring the value properly or scoping an ignore_changes. Tip: before opening the issue, compare the real value in the cloud with the one you asked for (§10.3). If they differ, it is normalisation.
Using ignore_changes = all to silence an error. You switch off management of every attribute of that resource: Terraform will stop detecting that somebody changed the instance size, the rules or the encryption. Tip: name the exact attributes, one by one, with a comment saying why and when to revisit it.
Editing inside .terraform/modules/ and forgetting about it. The next init wipes it, and in the meantime you are debugging code that is not the code that will be deployed. Tip: use that edit only to confirm a hypothesis, note the result, and fix at the source or in the call.
Accepting -migrate-state just to get rid of Backend configuration changed. It is the fastest way to write one environment's state over another's. Tip: when all you did was switch environments in the same directory, what you want is -reconfigure. Before a real migration, run terraform state list against the target.
Relaunching a failed apply without looking at what was left half-done. An apply that fails halfway leaves the world in a partial state; retrying can duplicate non-idempotent resources or deepen the divergence. Tip: run terraform plan first to see what Terraform thinks is missing, and cross-check against the cloud. The procedure is in 09-03.
Pasting a complete error into a public chat or an issue. An AWS error message carries your role's ARN, the account number, the region and the naming scheme. Sometimes it carries more. Tip: replace the identifiers with placeholders (123456789012, ecomarket-ENVIRONMENT-...) and keep only the RequestID if you are going to talk to the provider's support.
Not keeping the RequestID. It is the first thing any cloud's support asks for and the first thing lost when the CI log expires. Tip: for API errors, extract and record the RequestID as part of the failed job's summary.
Exercises
Exercise 1: classify and diagnose six errors
For each of the following messages, state: (a) which phase it happens in, (b) whether it is core, provider or API, (c) what the most likely cause is, and (d) what the next command you would run is.
--- A --- │ Error: Failed to query available provider packages │ Could not retrieve the list of available versions for provider hashicorp/aws: │ no available releases match the given constraints >= 5.0.0, ~> 4.60
--- B --- │ Error: Unsupported attribute │ on infra/app/load_balancer.tf line 22, in resource "aws_lb_listener" "https": │ 22: certificate_arn = module.data.certificate_arn │ ├──────────────── │ │ module.data is a object │ This object does not have an attribute named "certificate_arn".
--- C --- │ Error: creating ElastiCache Replication Group (ecomarket-prod-cache): operation error │ ElastiCache: CreateReplicationGroup, https response error StatusCode: 400, RequestID: │ 1a2b3c4d-..., api error CacheSubnetGroupNotFoundFault: CacheSubnetGroup │ ecomarket-prod-cache-subnets not found.
--- D --- │ Error: Invalid for_each argument │ on infra/app/dns.tf line 18, in resource "aws_route53_record" "services": │ 18: for_each = toset([for s in aws_lb.services : s.dns_name]) │ ├──────────────── │ │ aws_lb.services is tuple with 3 elements │ The "for_each" set includes values derived from resource attributes that cannot be │ determined until apply.
--- E --- │ Error: Provider produced inconsistent final plan │ When expanding the plan for module.data.aws_db_parameter_group.main to include │ new values learned so far during apply, provider "registry.terraform.io/hashicorp/aws" │ produced an invalid new value for .parameter: block set length changed from 4 to 3.
--- F --- │ Error: deleting Security Group (sg-0a1b2c3d4e5f67890): operation error EC2: │ DeleteSecurityGroup, https response error StatusCode: 400, RequestID: ..., │ api error DependencyViolation: resource sg-0a1b2c3d4e5f67890 has a dependent object
Exercise 2: the three-in-the-morning AccessDenied
EcoMarket's prod apply fails in the pipeline with this message:
╷
│ Error: creating EC2 Launch Template (ecomarket-prod-app): operation error EC2:
│ CreateLaunchTemplate, https response error StatusCode: 403, RequestID:
│ 9f8e7d6c-5b4a-3210-fedc-ba9876543210, api error UnauthorizedOperation: You are not
│ authorized to perform this operation. User:
│ arn:aws:sts::123456789014:assumed-role/ecomarket-terraform-prod/github-actions-ecomarket-infra-9102
│ is not authorized to perform: ec2:CreateLaunchTemplate because no identity-based policy
│ allows the ec2:CreateLaunchTemplate action.
│
│ with aws_launch_template.app,
│ on infra/app/compute.tf line 18, in resource "aws_launch_template" "app":
│ 18: resource "aws_launch_template" "app" {
│
╵Additional facts:
- The same code applied successfully in
stagingan hour ago. - Nobody has touched the
ecomarket-terraform-prodrole in three weeks. - The PR only changed the instance type, from
t3.mediumtom6i.large.
Questions:
- What exactly does the closing phrase of the message tell you, and what does it rule out?
- What is the contradiction between the facts and the message, and what hypothesis does it generate?
- Write the three commands you would run, in order, and say what you expect from each.
- If
simulate-principal-policyreturnedallowed, what would you conclude?
Exercise 3: the error that only shows up in prod
EcoMarket deploys a new prod-dr environment (disaster recovery) in eu-central-1, reusing exactly the same code that has worked for eighteen months in prod. The first apply fails:
╷ │ Error: Invalid count argument │ │ on infra/app/certificates.tf line 34, in resource "aws_route53_record" "validation": │ 34: count = length(aws_acm_certificate.main.domain_validation_options) │ │ The "count" value depends on resource attributes that cannot be determined until apply, │ so Terraform cannot predict how many instances will be created. ╵
Questions:
- Why has this code been working for eighteen months in
prodand fails inprod-dr? - What would have happened if the team had destroyed and recreated
prodat some point during those eighteen months? - Propose the permanent fix (strategy 1 of §7.3), writing the HCL.
- What check would you add to EcoMarket's pipeline so that this class of error is never again discovered on the first deployment of a new environment?
Solutions
Solution 1
A. (a) init. (b) Core (dependency resolution). (c) Two incompatible constraints: something requires >= 5.0.0 and something requires ~> 4.60 (that is, < 5.0). Almost certainly your root moved up to version 5 and a module is still pinned to 4, or the other way round. (d) terraform providers, which prints the constraint tree per module and points at who contributes each one.
B. (a) validate/plan. (b) Core. (c) The data module does not declare an output "certificate_arn". The fact that the certificate exists inside the module is irrelevant: a module's surface is its outputs (§6.2). (d) grep -rn "^output" modules/data/*.tf — or terraform console with keys(module.data) — to see the real surface. The fix is to add the output in the module, not to change the call.
C. (a) apply. (b) API (AWS). (c) There are two hypotheses and it is worth telling them apart. The first is eventual consistency: the subnet group is created in the same apply and ElastiCache cannot see it yet. The second, and more likely if the message names the group by its exact name: a dependency is missing from the code, because the resource references the group by its literal name instead of by aws_elasticache_subnet_group.main.name, and so Terraform does not know there is an ordering. (d) terraform state list | grep elasticache_subnet_group and grep -n "subnet_group_name" infra/data/*.tf. If the reference is literal, that is the cause and the fix is to reference the resource.
D. (a) plan. (b) Core. (c) The for_each takes its values — which in a toset are also the keys — from dns_name, an attribute that does not exist until the load balancers are created. (d) There is no command: there is a rewrite. The keys must come from the variable that defines the services: for_each = var.services and, inside, records = [aws_lb.services[each.key].dns_name].
E. (a) apply. (b) Provider. (c) block set length changed from 4 to 3: you declared four parameters and the provider returned three. The near-certain cause is that one of the four holds the engine's default value, and the RDS API does not store it because it is not a real modification. (d) aws rds describe-db-parameters --db-parameter-group-name ecomarket-prod-... --source user to see which ones were really recorded; the missing one is the one that is redundant in your configuration. Note: the error occurs inside module.data, so the fix goes in the module or in the values you pass to it.
F. (a) destroy (or an apply that replaces). (b) API. (c) Something Terraform does not manage is using that security group: a Lambda-in-VPC network interface, an instance launched by hand, another team's endpoint. (d) aws ec2 describe-network-interfaces --filters "Name=group-id,Values=sg-0a1b2c3d4e5f67890" to see exactly what is using it. If it is a Lambda interface, it takes a few minutes to release itself after the function is deleted.
Solution 2
1. What the closing phrase says. because no identity-based policy allows the ec2:CreateLaunchTemplate action is precise information and it rules out a lot:
- It is not an SCP. An organisational denial would say
with an explicit deny in a service control policy. - It is not an explicit
Denyin any policy. That would saywith an explicit deny in .... - It is not an identity problem. The ARN confirms that
ecomarket-terraform-prodwas assumed in account...14, which is the right one for production.
What it says is literally: an Allow is missing. The role's policy does not cover that action.
2. The contradiction and the hypothesis. If nobody touched the role in three weeks and the code works in staging, the question is what this apply does that the previous one did not. And the answer is in the PR: changing from t3.medium to m6i.large should not change permissions... unless this apply is the first one that creates a launch template.
The main hypothesis: the instance-type change forces the replacement of aws_launch_template.app. Replacing means creating a new one, and ec2:CreateLaunchTemplate is an action the prod role had never needed, because the template was created eighteen months ago, probably by hand or with a different role. It did work in staging because the staging role is more permissive — as it usually is — or because it was recreated there recently.
The secondary hypothesis, which must be ruled out just the same: the apply step ran with the plan role. The ARN says ecomarket-terraform-prod, not ecomarket-terraform-plan-prod, so this one is ruled out by the message itself. It is an example of why reading the whole ARN saves time.
3. The three commands.
# 1. Confirm that the prod role does NOT have the action and that
# staging's DOES. The comparison is the proof.
aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::123456789014:role/ecomarket-terraform-prod \
--action-names ec2:CreateLaunchTemplate ec2:CreateLaunchTemplateVersion \
--query 'EvaluationResults[].{action:EvalActionName,decision:EvalDecision}'
# I expect: "implicitDeny" for CreateLaunchTemplate.# 2. Confirm the replacement hypothesis: does the plan DESTROY and CREATE
# the template, or only create a new version?
terraform show -json plan.tfplan \
| jq -r '.resource_changes[]
| select(.address | contains("launch_template"))
| {addr: .address, actions: .change.actions, reason: .change.replace_paths}'
# I expect: actions ["create","delete"] and a replace_paths pointing at
# the guilty attribute.# 3. Verify in CloudTrail that this action had never been run
# with this role, which explains why the permission was never missed.
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=CreateLaunchTemplate \
--start-time "$(date -u -d '90 days ago' +%Y-%m-%dT%H:%M:%SZ)" \
--query 'Events[].{time:EventTime,who:Username}' --output table
# I expect: empty, or events from a different role (a human, or the old role).4. If the simulation said allowed. That would be the §8.3 signal: the account's identity policy does allow the action, so the block comes from something simulate-principal-policy does not evaluate. The candidates, in order:
- An SCP on the organisational unit. But the message would have said
explicit deny in a service control policy, so that would be odd. - A permissions boundary on the role. That does not fit the message's wording either.
- A policy condition that is not met. This one does fit:
simulate-principal-policyevaluates without condition context unless you pass it in. If the policy hasCondition: { StringEquals: { "aws:RequestTag/Project": "EcoMarket" } }and the resource does not carry that tag, the simulation saysallowedand reality denies.
The correct action in that case would be to repeat the simulation with --context-entries reproducing the conditions, and compare the tags local.common_tags applies with the ones the policy requires. At EcoMarket this is a real cause: the prod policy requires the Owner tag, and a resource that was left without tags = local.common_tags fails with an AccessDenied that looks like a permissions problem and is a tagging problem.
Solution 3
1. Why it worked in prod and fails in prod-dr.
Because in prod, aws_acm_certificate.main already exists in the state. Terraform reads its attributes during the refresh, and domain_validation_options is therefore a known value at plan time. length() over a known value gives a known number, and count is satisfied.
In prod-dr there is no state: the certificate is going to be created in this very apply. Its domain_validation_options is (known after apply), length() of an unknown value is unknown, and count cannot be unknown.
The code was always wrong. What hid the error is that prod's first apply happened eighteen months ago, probably in two steps with -target, and nobody created the environment from scratch again. It is exactly the trap described in §7.2: this error does not appear on incremental applies, only on creation from scratch.
2. If they had recreated prod. They would have hit the same error, in production, probably during an incident when they were in a hurry. It is the very scenario disaster-recovery environments are built for, and discovering that the code does not deploy from scratch precisely when you need it is the worst way to discover it.
That turns the exercise into an operational argument: an environment that has never been created from scratch is not tested, even if it has been in production for eighteen months.
3. The permanent fix.
# infra/app/certificates.tf
# The keys come from here: literals in the code, ALWAYS known,
# on the first apply and on the thousandth.
locals {
domains = toset([
"ecomarket.example.com",
"www.ecomarket.example.com",
"api.ecomarket.example.com",
])
}
resource "aws_acm_certificate" "main" {
domain_name = "ecomarket.example.com"
subject_alternative_names = [
for d in local.domains : d if d != "ecomarket.example.com"
]
validation_method = "DNS"
tags = local.common_tags
lifecycle {
create_before_destroy = true
}
}
data "aws_route53_zone" "main" {
name = "ecomarket.example.com"
private_zone = false
}
resource "aws_route53_record" "validation" {
# for_each over a set of literals: at PLAN time Terraform knows
# there will be exactly three records and what each one is called.
for_each = local.domains
# These three values ARE unknown at plan time, and that is
# allowed: an argument may be (known after apply); a key may not.
name = one([
for o in aws_acm_certificate.main.domain_validation_options :
o.resource_record_name if o.domain_name == each.value
])
type = one([
for o in aws_acm_certificate.main.domain_validation_options :
o.resource_record_type if o.domain_name == each.value
])
records = [one([
for o in aws_acm_certificate.main.domain_validation_options :
o.resource_record_value if o.domain_name == each.value
])]
zone_id = data.aws_route53_zone.main.zone_id
ttl = 60
allow_overwrite = true
}
resource "aws_acm_certificate_validation" "main" {
certificate_arn = aws_acm_certificate.main.arn
validation_record_fqdns = [for r in aws_route53_record.validation : r.fqdn]
timeouts {
create = "15m"
}
}The three changes that matter, and why:
for_each = local.domainsinstead ofcount = length(...). The keys are literals. The plan can enumerate the three records by name (["api.ecomarket.example.com"], and so on) before anything is created.one([for ... if ...])to look inside the unknown attribute. It is legal because the result is a value, not a key. Andone()fails loudly if the lookup returns more than one element, which turns unexpected data into a clear error rather than odd behaviour.- Stable addresses as a side effect. With
count, the addresses are[0],[1],[2], and adding a domain at the start of the list shifts all the others, destroying and recreating DNS records. Withfor_each, the address is["api.ecomarket.example.com"]and adding a domain only adds a resource. Fixing the error also fixes, along the way, a stability problem nobody had noticed.
4. The check to add to the pipeline.
The underlying problem is that no environment is ever created from scratch, and so the first-apply path is untested. Two measures, from cheapest to most expensive:
# .github/workflows/deploy-from-scratch.yml
# Weekly: create EVERYTHING from scratch in a throwaway account,
# and destroy it when finished. It is the only test that exercises
# the first-apply path.
name: Deploy from scratch
on:
schedule:
- cron: '0 3 * * 1' # Monday, 03:00 UTC
workflow_dispatch:
jobs:
from-scratch:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/ecomarket-terraform-dev
aws-region: eu-west-1
- name: Deploy a complete ephemeral environment
run: |
export TF_VAR_environment="ephemeral-${GITHUB_RUN_ID}"
terraform -chdir=infra/app init -backend=false
terraform -chdir=infra/app apply -auto-approve \
-var-file="$PWD/environments/common.auto.tfvars"
- name: Always destroy
if: always()
run: terraform -chdir=infra/app destroy -auto-approveAnd the cheap measure, which catches the same problem without deploying anything: a terraform test test with mock_provider (07-03). With mocked providers there is no prior state, so every resource attribute is unknown and the invalid count fails in the test, in seconds and at no cost:
# tests/plan_from_scratch.tftest.hcl
mock_provider "aws" {}
variables {
environment = "test"
environments = { test = { db_class = "db.t4g.micro", storage_gb = 20,
multi_az = false, retention_days = 1,
protect_deletion = false, extra_tags = {} } }
}
run "the_from_scratch_plan_is_valid" {
command = plan
# No asserts: if the plan cannot be computed without prior state,
# the test fails, and that is exactly the failure we want to catch.
}The general lesson of the exercise, which is worth more than the HCL: a plan that works against existing infrastructure does not prove that the code deploys from scratch, and that is one of the few properties a Terraform pipeline does not verify by default.
Conclusion
This lesson has been both the catalogue and the method, and it is worth separating what needs memorising from what needs internalising. The catalogue is looked up; the method is practised.
- A Terraform error message has five parts and each one carries a different kind of information. The summary is the category, not the cause; the
on <file> line <N>reference says where it was detected, not where the problem is; the configuration snippet tells you whether you are looking at the code you think you are; and the detail, which is the part nobody reads, usually carries the suggestion or the command that closes the diagnosis. - The method is five questions before you look at the catalogue: which phase is failing, whether the message comes from core, the provider or the API, whether it reproduces locally, what changed since the last time it worked — and that "what" includes the lock file and the modules' versions, not just your
git log— and how to reduce it to the smallest case. - The phase narrows the search space better than anything else.
initis environment;validateis code without credentials;planhas touched nothing and you can experiment;applyhas modified part of the world, and the first question is no longer why it failed but what was left half-done. initerrors are environment errors, not logic errors: a misspelled provider thatterraform providerslocates in the tree; version constraints with no intersection coming from modules you did not write; a lock file with no hashes for the runner's platform; aBackend configuration changedthat almost always wants-reconfigureand almost never-migrate-state; and a Git module whose real cause is in the innermost line of the message.- Syntax and type errors are the good ones, because
validatecatches them without credentials and in seconds. The recurring surprise is thatUnsupported argumentandUnsupported attributeare often not typing mistakes but provider version mismatches, andterraform providers schema -jsontells them apart in ten seconds. Unsupported attributeon a module has an explanation that is hard to accept: a module, seen from outside, is not its code, it is exactly the set of itsoutputs. The resource existing inside does not make it accessible.- A
Cycleis broken by extracting the relationship into a separate resource, and its most frequent artificial cause is adepends_onon amoduleblock, which couples everything to everything. - The unknown-values error is the deepest in the language. Terraform needs to enumerate the instances in the plan so that the plan is reviewable, and that is why
countandfor_each's keys cannot be unknown — even though the values can be. The mnemonic: you supply the keys; the cloud supplies the values. And the operational corollary, which comes out of exercise 3: this error only appears when creating an environment from scratch, so an environment that has never been created from scratch is not tested. AccessDeniedis diagnosed in four steps: identity, action, account policy, hierarchy policy. The fact that changes everything is thatsimulate-principal-policydoes not evaluate SCPs: if the simulation saysallowedand reality denies, the cause is outside the account and you have just eliminated the whole search space inside it. When you do not have permissions to climb higher, a ticket to the security team with five concrete data points turns two days into two minutes.- Terraform retries transient errors and does not retry deterministic ones. If the message says
exceeded maximum number of attempts, 25, relaunching will not help. And eventual consistency is resolved by waiting for the condition — a_validationresource, an_attachment, atimeoutsblock — never for the clock. This is a bug in the provideris formally true and practically misleading: half the time it is the API normalising a value. Before reporting, compare what you asked for with what the cloud stored. And if it has to be silenced,ignore_changeson the exact attribute, with a comment and a review date, neverall.- When the error points at
.terraform/modules/or.terragrunt-cache/, the path is the answer to "is this mine?".modules.jsongives you the exact version that was downloaded — which is the usual explanation for "I didn't change anything" — andterragrunt render-jsonmakes visible the composition ofinputsthat produces an error whose cause is threeincludes further up. - And CI errors are not looked for in the code: they are looked for in the differences. No TTY, no colour, a different version, different credentials, a cold cache, a lock file without the runner's platform, a clock five minutes fast. A fifteen-line diagnostics block at the start of every job turns a twenty-message conversation into a two-message one.
One important thing is left out. This whole catalogue assumes the error message tells you something. Sometimes it does not: the apply fails with a generic provider error, or hangs with no message, or the plan says it is going to replace a resource and there is no way to see why. That is where reading messages ends and instrumentation begins.
The next lesson, Debugging Terraform, is the toolbox: TF_LOG in depth — its levels, the separation between core and provider, and the security warning about why it is off in CI — how to read a 4,000-line trace down to the twelve lines that matter, terraform console as an expression debugger, the plan in JSON to know exactly what is unknown and who makes it unknown, terraform graph to see a cycle, how to isolate a nested module in a minimal directory, how to reproduce a runner's environment, and what to do when the thing that blows up is Terraform itself.
