Follow References Before Adding Depends On
Two trades share one wall. The electrician's first fix must finish before the drywaller closes it, but nothing in the drywaller's materials list mentions electricity, so the order exists only in the schedule. Terraform's schedule is a graph, and the graph comes from references rather than from the order of the blocks.
The example is orders-api: a load balancer named orders-api-prod, a target group, an HTTPS listener, an ACM certificate and its validation object, an S3 bucket for attachments, and an IAM role plus policy attachment for access logs. One service, one name that must be unique in the account and region.
The first apply failed at the listener with CertificateNotFound. The certificate existed; the validation record did not. The fix that landed added depends_on to four resources. The plan went green and became slower and noisier, with attributes known at plan time turning into values known only after apply.
The reference was already there: certificate_arn = aws_acm_certificate_validation.api.certificate_arn. That expression is an edge. The listener cannot be planned until the validation object produces its ARN. The mistake was in which object was referenced, not in a missing depends_on.
A reference creates an edge for one of three reasons, and all three look the same in the graph: the dependent uses a computed attribute such as an ARN or an IP address; the dependent needs the object to exist before an API call succeeds even though no value passes; or a module input or output carries the value. Core collects every edge, rejects cycles, and starts any node whose dependencies are satisfied, ten at a time by default.
Figure 1 draws the graph. The certificate chain feeds the listener, the target group needs nothing before it, and one dotted edge is the only explicit dependency in the configuration.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
ROLE["aws_iam_role.lb_logs"] --> ATT["aws_iam_role_policy_attachment.lb_logs"]
CERT["aws_acm_certificate.api"] --> VAL["aws_acm_certificate_validation.api"]
LB["aws_lb.api
orders-api-prod"] -->|"load_balancer_arn"| LSN["aws_lb_listener.https"]
VAL -->|"certificate_arn"| LSN
TG["aws_target_group.api"] -->|"target_group_arn"| LSN
ATT -.->|"depends_on for access-log policy"| LB
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class LB,CERT primary;
class VAL,TG,LSN secondary;
class ROLE ok;
class ATT warn;
The dotted edge is the justified case. Nothing on aws_lb.api refers to the policy attachment, but access-log delivery fails until the role may write to the bucket. No attribute carries that fact, so the configuration states the order: one attachment, one load balancer, one comment explaining why.
Hidden dependencies come in two kinds. One leaves a side effect and no attribute; the other is only propagation delay.
One narrow edge, or none
A side effect with no shared attribute — an IAM attachment before a service assumes a role, a bucket policy before objects are written — deserves one narrow edge and a comment naming the effect. Propagation delay does not: depends_on waits for every action on the dependency, including reads, but not for IAM to replicate a policy, DNS to become visible, or a service-linked role to appear. Those need a retry or a check, not another edge.
Module scope is where the argument gets overused. A depends_on on a module call orders every resource in one module behind every resource in another.
A module edge orders everything
Terraform warns that module-level depends_on produces conservative plans and can replace more than necessary, because pending upstream changes make downstream values unknown. The usual repair is to pass the one output the module needs and delete the argument.
Figure 2 puts the three cases side by side: the reference edge that should carry the relationship, the side effect that justifies an explicit one, and the module blanket that hides the real reference.
Know What Forces Replacement in Your Provider
Renaming the load balancer looked like an edit: one string, orders-api-prod to orders-api-v2, and a console can do it. The plan said otherwise:
# aws_lb.api must be replaced
-/+ resource "aws_lb" "api" {
~ name = "orders-api-prod" -> "orders-api-v2" # forces replacement
~ arn = "arn:aws:elasticloadbalancing:..." -> (known after apply)
~ dns_name = "orders-api-prod-1234.us-east-1.elb.amazonaws.com" -> (known after apply)
# (12 unchanged attributes hidden)
}
The marker is -/+, and the attribute carries # forces replacement. The load balancer API has no rename call: the name belongs to the create request, so the only way to change it is to build a new object. Nothing in the size of the diff tells you that; the provider schema does.
Read a plan in three passes:
| Pass | Look for | What it tells you |
|---|---|---|
| Action | +, ~, -, -/+ | create, update in place, destroy, or replace |
| Force | # forces replacement | the provider cannot change that argument in place |
| Downstream | (known after apply) | a new identity replans every dependent |
The schema is the authority, and it is already on disk. terraform providers schema -json prints every resource type and, for each argument, whether a change requires a new object. The registry page marks the same arguments, usually with a "forces new resource" note. The provider changelog is where a mutable argument quietly becomes immutable — a behaviour change with no version change in your configuration.
Replacement does not always start with an edit. A refresh can discover an out-of-band change to an immutable attribute; a provider upgrade can reclassify one; lifecycle.replace_triggered_by can cascade a replacement; -replace requests one directly. Figure 3 follows the decision, including the two failures worth planning for: a schema error before any API call, and a name or quota collision during the replacement.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Argument differs from state"] --> B{"Argument exists in the
installed provider schema?"}
B -->|"no"| B1["Validate or plan error:
unsupported argument"]
B -->|"yes"| C{"Schema marks it
ForceNew?"}
C -->|"no"| D["~ update in place
same id"]
C -->|"yes"| E["-/+ replacement proposed"]
E --> F{"Lifecycle blocks
the destroy?"}
F -->|"prevent_destroy"| F1["Plan rejected until
the rule is removed"]
F -->|"create_before_destroy"| G["Create replacement,
then destroy old"]
F -->|"neither"| H["Destroy old,
then create replacement"]
G --> I{"Name, quota and
health allow two?"}
I -->|"no"| I1["Apply fails at create:
duplicate name or quota"]
I -->|"yes"| J["New id and ARN recorded
dependants replanned"]
H --> J
D --> K["No gap in service"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,E,B,C,F,I primary;
class G,H,D,J secondary;
class K ok;
class B1,I1 danger;
class F1 warn;
The habit that follows: before applying any change to a named object, find # forces replacement, then look for the name. A replacement that keeps the name and destroys first has a gap; one that creates first has a collision. Both are avoidable if you noticed before the apply.
Create Before Destroy Changes Order, Not Service Guarantees
By default a replacement destroys the old object and then creates the new one. create_before_destroy = true reverses that order for the resource it is declared on:
The intent is sound; the effect is not confined to the listener. While the listener moves from port 8443 to 443 — a replacement-triggering change — the old listener should keep answering until the new one exists. The lifecycle documentation states that Terraform propagates the rule to the resource's dependencies and records it in state. The listener depends on the load balancer, the target group and the certificate validation, so all three inherit it, and you cannot set it back to false on the load balancer without implying a cycle.
The name collides before the health gate
Because the rule propagates, aws_lb.api now creates its replacement before destroying the original, and both would be called orders-api-prod. AWS rejects the second create with a duplicate-name error. The apply stops with the old load balancer still serving and no new object in state. That is a better failure than an outage, but it is still a failed change, and another lifecycle flag will not fix it.
Three patterns make two objects coexist, and each costs something.
| Pattern | How it works | What it costs |
|---|---|---|
| Generated suffix | name_prefix where the type offers it, or a random_id appended to the name | gives up the stable name dashboards and runbooks use; a stable alias such as a DNS record has to take over |
| Separate identity object | one object owns the stable identity while the load balancer's name stays disposable | one more object to own and wire |
| Blue-green pair | orders-api-blue and orders-api-green | the honest option when the name cannot change at all, and the most expensive to operate |
Capacity is easier to miss. Two objects exist at once: two load balancers against an account quota, two fleets against a vCPU limit, two elastic IPs, twice the cost for the duration. Plans reserve nothing, so a quota that looked fine can still reject the create. Request the increase before the change, not during the incident.
Order is not a health gate
The flag changes the order of two API calls; it does not wait for healthy targets, a trusted certificate, or a boot check. A listener can be created and still route to an empty target group. The health gate has to be explicit: a postcondition, a check that probes the endpoint, or a pipeline that shifts traffic after a health signal.
One more behaviour: when the resource has a provisioner that runs during destroy, create_before_destroy prevents it from running. Cleanup scripts that drain a node silently stop executing, so that work has to move somewhere the flag does not reach.
Prevent Destroy and Ignore Changes Have Narrow Boundaries
prevent_destroy is a brake on one address. It rejects any plan that would destroy the object there — a rename fails at plan time with "Instance cannot be destroyed", before any write. For a database, a bucket under legal hold, or the load balancer in front of revenue, that is the intended effect.
The brake also applies to terraform destroy and -replace. Neither gets a special exemption.
Three boundaries cause real incidents.
Removing the block still destroys the object. Apart from create_before_destroy, Terraform does not record lifecycle rules in state. Delete the resource block and the next plan proposes a destroy; the guard left with the code. A large deletion diff therefore means "protection removed and object destroyed", which is why the removal deserves its own change.
The guard is local to this state. A second root module, a console session, or another team's pipeline is not constrained by your configuration. Two states managing one object is already a defect, but prevent_destroy neither detects nor compensates for it. Shared ownership needs an owner outside Terraform: a policy, a tag, a catalog entry, or an IAM boundary that denies deletion.
It blocks legitimate replacements. The flag cannot distinguish an accidental deletion from a required new object after an AMI change. The rule must be removed in a reviewed diff, applied, and restored. That visibility is a feature, but it means prevent_destroy is not a background net you can forget.
ignore_changes has the opposite shape. It is narrow by construction and easy to widen by accident: it takes attribute names relative to the resource, ignores them when planning updates, and applies them normally when planning a create.
ignore_changes = [tags] lets a tagging agent own the tag map; ignore_changes = all lets Terraform create and destroy the object but never update it.
The documented use is shared management, and it depends on a contract outside the code: who writes the attribute, which values they may touch, and what happens when the two disagree. Without that, ignore_changes hides drift instead of resolving it. The object changes, the plan stays clean, and the repository slowly stops describing reality.
Two failure modes are worth naming. Ignoring a replacement-triggering attribute suppresses the replacement itself: an out-of-band rename would produce no diff, and the object would keep a name the configuration no longer claims. Ignoring security-relevant attributes — public-access flags, encryption, ingress rules — turns a guardrail into an invisible exception. Keep the list short, commented, and reviewed like code.
| Control | What it guarantees | Where it fails | Pair it with |
|---|---|---|---|
depends_on | Every action on the whole dependency completes before every action on the dependent | No attribute-level edges, more conservative plans, unknown values, and no wait for IAM or DNS propagation | A reference to the attribute that carries the value |
create_before_destroy | The replacement is created before the original is destroyed | No health gate, no capacity reservation, unique-name collisions, and propagation to every dependency | Generated names, reserved quota, and an explicit post-apply health check |
prevent_destroy | Any plan that would destroy or replace this object is rejected while the block exists | Removed with the resource block, bypassed by another state or a console, and blocks valid replacements | A documented removal procedure and an owner outside Terraform |
ignore_changes | Listed attributes are not compared during update planning | Hides real drift, including replacement-triggering drift, and cannot cover meta-arguments | A named external writer and a check that reports the drift |
precondition | The change to this object stops before it starts when an assumption is false | Values unknown at plan time defer the check to apply, after other objects may exist | Input variable validation for values known before planning |
check | A failed assertion is reported at the end of plan and apply | It never blocks or reverts anything, and a warning is easy to miss in a long log | CI or HCP Terraform alerting on failed checks |
Enforce Assumptions with Preconditions and Postconditions
Terraform offers four mechanisms for stating an assumption, and they differ in when they run and whether they can stop the operation.
Input variable validation runs before a plan exists. It sees only the variable's own value, so it suits format and range rules: a service name that must match a pattern, a replica count that must be at least two.
Preconditions block before the change. A precondition is evaluated while the plan is built, before the object's arguments reach the provider, so a failure stops that object's planned action.
Postconditions block after it. A postcondition is evaluated after the change is planned and applied; a failure prevents changes to anything that depends on the object. Both can reference other objects in the module, and the postcondition can use self for the object's resulting attributes.
check blocks run last, at the end of plan or apply, and never block. A failed assertion is a warning and the operation continues. That is a different instrument, not a weaker one: a check can read a live endpoint through a nested data source, so it answers "is the service healthy?" rather than "did the object get created?".
The unknown-value rule decides where a condition helps. If the value is known during planning, the check runs then. If it only exists after the apply, Terraform defers the check to apply. A deferred precondition still stops that object's planned action; a deferred postcondition stops downstream work but does not undo what already happened. The object stays in state, which is honest: it exists, and the guarantee about it failed.
The configuration below applies all three ideas to orders-api. The precondition reads a data source, so it is evaluable at plan time. The postcondition reads self.availability_zones, so it runs after creation. The check probes the service, which is the only one that can say whether traffic is being served.
Enforce Assumptions with Preconditions and Postconditions
Execution status: design-only. Terraform CLI 1.17.1 and AWS provider 6.72.0 were current on 5 November 2026. The ordering below follows the documented behaviour; no AWS apply was performed for this article.
Prerequisites. A disposable AWS account and region, a VPC with at least two private subnets tagged Tier = private in different availability zones, and credentials that can create a load balancer. Add the hashicorp/http provider for the check, and run it from a network that can reach the internal load balancer.
Minimal setup. One root module with the variables, data source, load balancer, and check below.
variable "service_name" {
type = string
default = "orders-api"
}
variable "vpc_id" {
type = string
}
data "aws_subnets" "private" {
filter {
name = "vpc-id"
values = [var.vpc_id]
}
filter {
name = "tag:Tier"
values = ["private"]
}
}
resource "aws_lb" "api" {
name = "${var.service_name}-prod"
internal = true
load_balancer_type = "application"
subnets = data.aws_subnets.private.ids
lifecycle {
precondition {
condition = length(data.aws_subnets.private.ids) >= 2
error_message = "orders-api needs at least two private subnets tagged Tier=private in ${var.vpc_id}; found ${length(data.aws_subnets.private.ids)}."
}
postcondition {
condition = length(self.availability_zones) >= 2
error_message = "The load balancer landed in ${length(self.availability_zones)} availability zone(s); orders-api requires at least two."
}
}
}
check "orders_api_health" {
data "http" "health" {
url = "https://${aws_lb.api.dns_name}/health"
}
assert {
condition = data.http.health.status_code == 200
error_message = "orders-api health endpoint returned ${data.http.health.status_code}."
}
}
- Run
terraform validate. It passes: every block is well formed and every reference resolves. That proves syntax and types, not the assumptions. - Point
var.vpc_idat a VPC with one matching subnet and plan. The precondition fails during planning, before any create or update call, and no object is created. - Add a second tagged subnet in another zone and plan again. The precondition passes; the postcondition cannot run because
availability_zonesis unknown, so the plan shows(known after apply). - Apply. The postcondition is evaluated against
self.availability_zones. If it passes, the apply completes and the address is recorded in state. - Break the check: point
urlat/missingand apply. The assert fails, Terraform prints a warning, and the operation finishes. Nothing rolls back. - Break the precondition again on the existing object. Expect the step 2 error and no replacement, because the precondition runs before the change.
Expected observation. Failures split into three shapes: a blocking error at plan time, a blocking error at apply time after the object exists, and a warning that changes nothing. Each message names the object and the actual value.
Failure checks. A self reference in a precondition is an error, not a failed assertion. A check that reads the load balancer directly instead of through a nested data source warns that the value is known only after apply.
A postcondition over a post-apply value moves to the apply phase rather than failing early. When it fails there, the load balancer is already recorded in state and only downstream work stops.
Cost dimensions. The load balancer and its data processing are billable while they exist; the check adds one HTTPS request per plan and apply.
Cleanup. Run terraform destroy, confirm the load balancer is gone, and delete state and plan files. If destroy is blocked, look for a prevent_destroy rule added during the exercise.
Figure 4 places the mechanisms on one timeline and marks which ones can stop the operation. The left column blocks; the right column only reports. The band underneath is the surprise: an unknown value moves the decision later without making it weaker.
The difference in authority is the point. A condition is a claim you will fail the change over. A check is a claim you want recorded and alerted on. Using a check where a precondition belongs gives you a green pipeline and a broken service; using a precondition where a check belongs turns a transient probe failure into an outage of your deployment process.
Replace a Degraded Object with a Reviewed Plan
Weeks later, orders-api returns 502s in one availability zone. The target group reports one unhealthy instance and the configuration has not changed. The object is degraded; the question is how to replace it without making the incident worse.
Diagnose first. Target health, the system log, and a data source read answer different questions, and the cheapest repair is often not a replacement: re-register the target, restart the process, fix a security group rule. Replacing an instance discards local volumes, resets identity, and forces every dependent to replan. Replace when the object is unrecoverable, not when it is unhappy.
When replacement is the decision, request it inside a plan:
terraform plan -replace=aws_instance.api[0] -out=replace.tfplan
The plan marks that address -/+ and says the replacement was requested. You can read the planned attributes, see which dependants will be replanned, and check the destroy order. Applying the saved file executes exactly what you reviewed.
taint writes outside the plan
terraform taint reaches the same replacement by a worse route: it writes a marker into state, outside any plan. The next plan anyone runs — a colleague, a CI job, an unrelated change — sees the marker and proposes the destroy. Nothing records why, and the review that would have caught a wrong address never happens. The taint documentation calls the command deprecated and recommends -replace for v0.15.2 and later, because the replacement belongs in the plan where it can be reviewed before it is externally visible.
Lifecycle rules still apply. prevent_destroy rejects the replacement plan, which is the guard working, and create_before_destroy only changes the order.
Identity changes either way. Anything holding the old ARN is replanned in the same run — one more reason to read the whole plan, not the single block.
Predict a replacement
Execution status: design-only. This is a prediction exercise; run it against your own disposable configuration and treat each expected marker as a hypothesis. Terraform CLI 1.17.1 and AWS provider 6.72.0 define the behaviour described.
Prerequisites. A disposable root module with one named object you can safely replace — the aws_lb.api example, or local_file.hello from the earlier local lab for zero cloud cost. A state file you can discard.
Minimal setup. Fill in the predicted column before running anything, then record what the plan actually said.
| Change | Predicted marker | Same object | Dependants replanned |
|---|---|---|---|
| Update a mutable tag | ~ | yes | no |
Change name on a named object | -/+ | no | yes |
-replace with no config change | -/+ | no | yes |
ignore_changes = [name], then change name | none | yes | no |
prevent_destroy plus -replace | error | yes | no |
create_before_destroy with a fixed name | -/+, then apply error | yes | not reached |
- Apply the baseline, then confirm a no-change plan with
-detailed-exitcodereturning0. - Change one mutable argument, plan, and confirm
~with an unchangedid. Apply and confirm the address survived. - Change the object's
nameand find# forces replacement. Do not apply; note which dependants show new unknowns. - Revert, plan with
-replace=<address> -out=replace.tfplan, inspect it withterraform show, then apply. Confirm the new identity and the replanned dependants. - Add
ignore_changes = [name], change the name, and plan. Expect no diff at all — the row that should make you uncomfortable. - Remove the ignore rule, add
prevent_destroy = true, and plan with-replace. Expect a plan error with the object intact. - Swap in
create_before_destroy = true, restore the fixed name, and apply a replacement. Expect a duplicate-name error at create, with the original still serving.
Expected observation. Four rows are the same object and the same kind of edit, and only the marker separates them. The matrix is the deliverable: it records what you expected before a plan existed.
Failure checks. A replacement with no force marker usually came from -replace, replace_triggered_by, or refresh drift. Read the plan's reason before assuming the configuration changed.
A prevent_destroy error during destroy means the rule is doing its job and needs a reviewed removal.
A create_before_destroy change that leaves the new object unhealthy means the flag worked and the health gate is missing.
Cost dimensions. The AWS rows create a billable load balancer and instance for the duration; a local_file version costs nothing. Plan files and state are sensitive either way.
Cleanup. Destroy with a reviewed plan, confirm the addresses are gone from terraform state list, and delete every saved plan. An interrupted replacement can leave an object that state does not record; find it in the console before retrying.
A reviewed replacement is the last control in the chain, and it depends on the earlier ones being honest. A -replace plan is only readable if the graph expresses the real dependencies, the lifecycle flags do not hide the destroy, and the conditions do not defer their verdict to a moment when nobody is watching.
Next in the Series
In Remote State, Locking and Environment Boundaries, we'll explore Design shared state access across S3, Azure, GCS and HCP without confusing locks with isolation.