Terraform core: state, plan/apply, lifecycle, providers, modules

State is the source of truth about what exists, the plan is the diff, and drift is the gap between them. Most Terraform incidents are state incidents.

Read the briefing
About 9 min to read 8 drills

What to remember

  1. State is the truth; the plan is the diff. Read the plan properly — the destroy lines especially.
  2. Remote state with locking, always. Two concurrent applies on local state is how infrastructure gets corrupted.
  3. State contains secrets. Encrypt it, restrict access, and treat it as a credential store.
  4. Refactor with moved blocks, not by hand. Renaming a resource without moving it means destroy-then-create in production.
  5. count versus for_each decides your blast radius. Removing an item from a count list re-indexes everything after it. Use for_each with stable keys.

The big picture

Terraform turns declared configuration into API calls by comparing it with state: a mapping from each resource address to a real object's identity and last-known attributes. Plan refreshes that mapping, computes a change set, and apply executes exactly that set; lifecycle rules, provider wiring, module boundaries, data sources, and count versus for_each all shape what that change set contains. Interviewers probe this node because reading a plan correctly, and knowing why state can lie, is what separates people who have applied Terraform from people who have recovered from it.

The mental model

Three documents, one diff. Configuration is desired state, state is Terraform's memory of what it created and what it looked like, and the provider is reality. Plan reads reality for every object in state (refresh), then diffs configuration against that refreshed memory, producing creates, in-place updates, replacements, and destroys. Anything reality holds that state does not is invisible; anything state holds that reality has lost is a phantom. Every Terraform failure story is one of those two.

In depth

State is a mapping, not a backup

State binds aws_instance.web to i-0a1b2c3d and caches the attributes the provider last returned. That binding is what lets plan say "update this one" rather than "create another one". Refresh re-reads every object already in state from the provider; it cannot discover an object Terraform never recorded. So an object created by hand, or created during an apply that was killed before the provider returned, shows up as + create on the next plan and a second copy gets made. terraform import (or an import block) writes the binding without touching the object; a clean plan afterwards proves configuration and reality agree.

The reverse failure is a lost update: two applies without locking, or a restored older state file, leave state describing objects that no longer match reality, so plan proposes updates or replacements that reconcile the wrong way, or destroys of things Terraform no longer really manages. The state document carries a serial that increments on every write and a lineage identifying its ancestry; terraform state push refuses a lower serial or a different lineage without -force, and a locking backend prevents the concurrent write in the first place.

The commands to know: terraform state list, terraform state show <addr>, terraform state pull | jq '.serial, .lineage', terraform state mv (re-address without touching reality), terraform state rm (forget without destroying). All of them are surgery; moved, import, and removed blocks are the reviewable, repeatable forms of the same operations and should be preferred in any codebase with more than one operator.

Plan and apply: reading the change set

terraform plan does three things: refreshes tracked objects, builds a dependency graph from references, and diffs configuration against refreshed state. The output symbols are the whole vocabulary: + create, - destroy, ~ update in place, -/+ destroy then create replacement, +/- create replacement then destroy (only with create_before_destroy), <= read a data source during apply. Inside a -/+ block the line marked # forces replacement names the argument the provider cannot change on the existing object; (known after apply) marks values that depend on something being created. The summary line counts a replacement as one add plus one destroy, which is why 1 to add, 1 to destroy can mean "delete the database".

terraform plan -out=tfplan saves the exact change set; terraform apply tfplan executes precisely that and nothing else, and is rejected as stale if state changed in between, which is the property CI relies on to make "the plan a human approved is the plan that runs" true. terraform show -json tfplan gives machines the same information for policy checks.

Useful flags, each with a caveat: apply -refresh-only writes reality's drift into state without changing infrastructure (plan -refresh-only only shows it; use it when someone tagged things by hand); -replace=<addr> forces a replacement without a configuration change (the successor to taint); -target=<addr> applies a subset and is an incident tool, not a workflow, because it leaves dependents unreconciled. Apply writes state per resource as each provider call returns, so an apply killed mid-wait can leave a real object with no state entry.

The lifecycle meta-arguments

lifecycle changes how a diff is applied, not what the diff is.

create_before_destroy = true flips replacement order from -/+ to +/-: the new object exists before the old one is removed, so an instance, launch template, or certificate can be swapped with no gap. It only works when two objects may coexist; a resource with a unique name (an S3 bucket, a security group named explicitly) cannot, and the create fails with "already exists". Terraform propagates the setting to dependencies so the ordering stays consistent.

prevent_destroy = true makes any plan that would destroy the address fail with "Instance cannot be destroyed". It stops terraform destroy, force-new replacements, and -target mistakes, and it is evaluated from configuration at plan time, so deleting the resource block deletes the guard too. Pair it with API-level protection.

ignore_changes = [tags["LastScanned"], desired_capacity] excludes listed attributes from the diff after creation, for values another system owns (an autoscaler, a tagging bot, a console-managed field). It does not apply to the initial create, and ignore_changes = all is a smell that usually means the resource should be a data source or should not be in Terraform.

replace_triggered_by = [aws_launch_template.app.latest_version] forces replacement when something else changes, and precondition and postcondition blocks assert invariants with a readable error. The interview move is to name the failure each one exists to prevent, then the case where it cannot help.

Providers: requirements versus configurations

Two different things share the word "provider". A provider requirement is declared per module:

terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.0" }
  }
}

init resolves the newest release inside the constraint and records the exact version and checksums in .terraform.lock.hcl, which is committed so every init on every machine selects the same binary until init -upgrade is run deliberately. A provider configuration is a provider "aws" { region = ... } block with credentials, region, default_tags, and optionally an alias, and it belongs in the root module.

A child module automatically inherits the root's default (un-aliased) configuration for each provider it requires. Aliased configurations never propagate implicitly: the child declares configuration_aliases = [aws.west] inside its required_providers, and the caller passes providers = { aws.west = aws.west }. The caller may also remap, providers = { aws = aws.west }, to run a module written for one region in another.

The anti-pattern is a provider block inside a reusable module. It works until someone adds count or for_each to the module call (not allowed for modules with their own provider configurations), and it fails badly when the module is removed: the resources' provider configuration vanishes with the block and Terraform cannot destroy them. Reviewers also check that credentials are not in the block (use the environment, a profile, or assume_role) and that alias names describe intent (aws.dr, aws.us_west), not people.

Modules, outputs, and data sources

A module is a directory of .tf files called with input variables and returning outputs. It cannot see the caller's resources or variables; everything crosses the boundary explicitly, which is what makes a module testable and what makes a leaky one (a hard-coded VPC id, an ARN from one account) fail everywhere else. Root-module outputs are the only values visible outside the configuration: to CI (terraform output -json), to other stacks via terraform_remote_state, or to humans.

Data sources read existing objects during plan: data "aws_vpc" "main" { tags = { Name = "prod" } } replaces a pasted vpc-0abc... and is re-read on every plan, so a change in the real object is picked up without a state edit. They are not managed; Terraform never creates, changes, or destroys what they read, and a data source that matches nothing (or two things) fails the plan with a clear error, which is a feature. When a data source depends on a value not known until apply, its read is deferred and the plan shows <= with (known after apply), which cascades unknowns into everything downstream; that is the usual reason a plan suddenly wants to replace things.

Cross-stack lookups have two styles. terraform_remote_state reads another root's outputs from its state (coupling you to its backend and exposing every output); provider data sources look up the object itself by tag or name (coupling you to a naming convention). Interviewers like hearing the tradeoff and a decision, and they listen for whether you know outputs are the module's contract, so changing one is a breaking change.

count versus for_each

Both create multiple instances of one resource block; they differ in how instances are addressed, and the address is the identity in state.

count = length(var.names) yields b[0], b[1], b[2]. Removing the middle element shifts every later element down one index, so the configuration at b[1] now describes a different object than the state at b[1]; if the argument that changed is force-new (a bucket name, an ECR repository name), the plan is -/+ on objects nobody meant to touch. for_each = toset(var.names) yields b["logs"], b["backups"], so adding or removing a key touches only that instance; each.key and each.value are the same for a set and differ for a map.

for_each keys must be strings known at plan time. A key derived from a resource attribute either churns (the IP changed, so the "old" record is destroyed and a "new" one created) or fails outright with "keys derived from resource attributes that cannot be determined until apply". Key on names humans chose.

count still has a place: count = var.enabled ? 1 : 0 as a feature toggle, or genuinely interchangeable instances where position is meaningless. Converting an existing count resource to for_each re-addresses every instance, so the PR must carry moved blocks from b[0] to b["logs"] and so on, or the conversion itself plans the destroy cascade it was meant to prevent. The check that catches all of this in review is a single question: what does the plan look like the first time someone removes an element?

Myths and facts

Myth: terraform refresh (or plan) will find resources someone created by hand.

Fact: Refresh re-reads only objects already in state. An untracked object is invisible and plans as a duplicate create; import is how it becomes tracked.

Myth: A -/+ replacement is not really a destroy.

Fact: It is a destroy followed by a create, in that order by default. For anything with data it is a deletion; prevent_destroy rejects it for exactly that reason.

Myth: Terraform creates the replacement before destroying the old object.

Fact: The default is destroy then create (-/+). Only create_before_destroy = true flips it to +/-, and only when two objects can coexist.

Myth: prevent_destroy is recorded in state, so it protects the resource even if the code changes.

Fact: It is configuration, read from the current code at plan time. Delete the block and the guard is gone; pair it with an API-level guard.

Myth: Child modules inherit every provider configuration, aliases included.

Fact: Only the default configuration is inherited. Aliases must be requested with configuration_aliases and passed with a providers map.

Myth: Data sources are resources Terraform happens not to own yet.

Fact: They are reads, re-run every plan, and never created, changed, or destroyed. A data source that matches nothing fails the plan rather than creating anything.

Myth: count and for_each are interchangeable ways to loop.

Fact: They differ in identity: positional versus keyed. Editing a list under count renumbers instances and can plan replacements of untouched objects.

How pros do it

  • Treat + on an object you believe exists as 'not in state', not 'does not exist'; check terraform state list and the cloud inventory before applying, and use import to reconcile.
  • Save the plan (plan -out), have a human or a policy read it, and apply that file; never approve on the summary line without reading every -/+ and # forces replacement.
  • Pin providers with ~> and commit .terraform.lock.hcl; keep provider configuration blocks in the root only and pass aliases explicitly.
  • Use for_each keyed on human-chosen names by default; reserve count for 0/1 toggles, and ship moved blocks with any change of address.
  • Prefer data sources or required inputs over pasted ids and ARNs so a module is portable across accounts and regions.
  • Put create_before_destroy on things that must not gap (instances behind a load balancer, certificates) and prevent_destroy plus provider deletion protection on things that hold data.
  • Use -target and state surgery only during incidents, write down what you did, and follow with a full plan that must be a no-op.

Questions people ask

Should I use count or for_each?

Answer with the identity rule, then the exception. for_each, keyed on names a human chose: the key is the instance's address in state, so an edit touches only that key, while count addresses by position, so removing one element renumbers everything after it and a force-new argument turns that into -/+. Keep count for var.enabled ? 1 : 0 toggles. Close with the caveat interviewers wait for: switching an existing resource needs moved blocks, or the switch itself destroys and recreates every instance.

What is the difference between ~, -/+, and +/- in a plan?

Say them in order and attach a consequence to each: ~ is an update in place; -/+ destroys the object and creates a replacement, in that order, so for anything stateful or serving traffic it is a deletion or an outage; +/- is the same replacement with the new object built first (create_before_destroy). Point at the # forces replacement marker as the line that names why. Finish with the trap: the summary counts a replacement as one add and one destroy, so 1 to add, 1 to destroy can be a database.

Does prevent_destroy stop terraform destroy?

Yes, and say what else it stops and what it cannot: any plan that would destroy the address fails with 'Instance cannot be destroyed', replacements and -target mistakes included. Then name the hole before they do: it is configuration read at plan time, so deleting the resource block or running state rm gets around it. Close by pairing it with deletion_protection (or the provider's equivalent) at the API and a CI check on planned deletes; layered guards is the answer being graded.

Why does my plan want to create a resource that already exists?

Lead with the mechanism, then the repair. State has no record of it: made by hand, or by an apply killed before the provider returned, and refresh only re-reads objects already in state, so it cannot find it. Import it (import block or terraform import) and expect a no-op plan for that address before applying anything else. 'Delete it and re-apply' and 'run refresh' are the two answers that lose the point.

Why can't my child module use aws.west?

Say the rule, then the wiring, then the anti-pattern. Aliased provider configurations are never inherited; only the default one is. The child declares configuration_aliases = [aws.west] in its required_providers and the caller passes providers = { aws.west = aws.west }. Then volunteer why a provider block inside a shared module is wrong: it forbids count and for_each on the call and orphans the resources when the module is removed.

Is terraform_remote_state or a data source better for cross-stack values?

Give the tradeoff and make a call. Data sources by tag or name once more than a couple of stacks are involved; remote state when a small team owns both sides. Remote state couples you to the other stack's backend and exposes every output; a data source couples you to a naming convention. Either way, say that outputs are a contract, so changing one is a breaking change; that sentence is what separates module users from module authors.

Why does a data source make my whole plan show (known after apply)?

Explain the deferral before offering a fix: one of the data source's arguments depends on something not created yet, so the read moves to apply and everything downstream becomes unknown, and unknown values can cascade into replacements, which is why a plan suddenly wants to rebuild things. Then the fix: give it inputs you control (a name or a tag), or split the stack so the object exists before it is read.

Further reading

Drills · 8

Answer in your head, or out loud, before you reveal. Mark each one: "Again" brings it back, "Got it" counts on your desk.

1 Pick the strongest answer

You inherit this block, already applied with var.names = ["logs", "backups", "exports"]:

resource "aws_s3_bucket" "b" {
  count  = length(var.names)
  bucket = "acme-${var.names[count.index]}"
}

A teammate deletes "logs" from the list and runs terraform plan. Walk me through what the plan shows, and why.

  1. Terraform re-indexes state automatically so only acme-logs is destroyed. Terraform never re-addresses state on its own; that takes moved blocks or terraform state mv.
  2. The shifted buckets are renamed in place with a ~ update. S3 bucket names are immutable, so a name change is a replacement (-/+) and the plan marks the line # forces replacement.
  3. aws_s3_bucket.b[2] is destroyed, and every instance whose index now maps to a different name is planned as -/+ (destroy and recreate), because count addresses are positional and bucket is a force-new argument. Removing an element shifts every later name down one index; each shifted instance's bucket name changes, and bucket names cannot be changed in place, so Terraform replaces them.
  4. Only the acme-logs bucket is destroyed; the others are untouched because Terraform matches instances by name. count instances are tracked by index, not by any argument's value; only for_each tracks by key.
In short

count tracks buckets by position, so removing one name shifts the rest and Terraform destroys and recreates the shifted buckets.

Why

count gives instances positional addresses (b[0], b[1], ...). Deleting an element does not delete "that instance"; it shifts every later element to a lower index, so the configuration at b[1] now describes a different bucket than the state at b[1], and a force-new argument change means destroy-and-recreate. for_each = toset(var.names) keys instances by value (b["logs"]), so removing a name touches only that key. Converting an existing count resource to for_each needs moved blocks (from = aws_s3_bucket.b[0], to = aws_s3_bucket.b["logs"]) or the same cascade happens once during the conversion. Interviewers also listen for the blast-radius aside: destroying a non-empty bucket fails unless force_destroy = true, which is the only thing that would have stopped this apply.

The common mistake

Answering that only the removed bucket is destroyed, because you are matching by name in your head while Terraform matches by index; or recommending for_each without moved blocks, which recreates every bucket once on the way over.

Read the docs

2 Answer out loud

What is Terraform state actually for, and give me two concrete ways a wrong or stale state produces a wrong plan. Two to five sentences: mechanism, not a definition.

In short

A strong answer says state maps each resource address to a real object, and anything missing from state is invisible to Terraform.

What a strong answer does
  • mechanism: State binds each resource address to a real object's identity and caches its attributes; plan refreshes those tracked objects, then diffs desired configuration against refreshed state, so state is the identity mapping and anything not in it is invisible.
  • failure modes: Two precise cases with the resulting plan shape: an untracked object (manual creation, or an apply killed before state was written) plans as + and yields a duplicate; a lost or restored older state plans updates, replacements, or destroys against objects whose real attributes differ. Notes that refresh only re-reads tracked objects.
  • communication: Leads with the mapping, then the two failure modes each with its plan symptom, no filler, precise vocabulary (address, refresh, serial).
Why

Interviewers listen for the word "mapping" (or binding, identity), for the sentence "plan is config versus refreshed state", and for the consequence that untracked objects are invisible. The two failure modes worth naming are the untracked object (plans as a duplicate create) and the lost update (state describes a past that is no longer true). Candidates who jump straight to "keep it in S3 with locking" have skipped the mechanism the backend exists to protect.

The common mistake

Opening with 'we keep it in S3 with DynamoDB locking'. That is the protection for the mapping, not the mapping; say what state is before saying where it lives.

Read the docs

3 Read the output

Read me this plan. If you apply it as-is, what happens to the instance and to the DNS record, in what order, and is there an outage?

$ terraform plan
aws_instance.web: Refreshing state... [id=i-0a1b2c3d4e5f60718]
aws_route53_record.web: Refreshing state... [id=Z0123456789ABCDEFGHIJ_web.example.com_A]

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  ~ update in-place
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # aws_instance.web must be replaced
-/+ resource "aws_instance" "web" {
      ~ ami                          = "ami-0c55b159cbfafe1f0" -> "ami-0e1d30f2c40c4c701" # forces replacement
      ~ arn                          = "arn:aws:ec2:us-east-1:123456789012:instance/i-0a1b2c3d4e5f60718" -> (known after apply)
      ~ id                           = "i-0a1b2c3d4e5f60718" -> (known after apply)
        instance_type                = "t3.medium"
      ~ private_ip                   = "10.0.1.23" -> (known after apply)
      ~ public_ip                    = "54.210.11.7" -> (known after apply)
        tags                         = {
            "Name" = "web"
        }
        # (24 unchanged attributes hidden)
    }

  # aws_route53_record.web will be updated in-place
  ~ resource "aws_route53_record" "web" {
        id      = "Z0123456789ABCDEFGHIJ_web.example.com_A"
        name    = "web.example.com"
      ~ records = [
          - "54.210.11.7",
        ] -> (known after apply)
        ttl     = 60
        type    = "A"
        # (3 unchanged attributes hidden)
    }

Plan: 1 to add, 1 to change, 1 to destroy.
  1. Nothing is destroyed: a replacement only happens if you run terraform apply -replace=aws_instance.web. A replacement planned from a configuration change applies with a plain terraform apply; -replace forces one when the configuration has not changed.
  2. The AMI is swapped on the running instance in place; only the DNS record is touched afterwards. # forces replacement next to ami means the provider cannot change it on the existing object; the whole instance is replaced.
  3. A new instance is created first, then the old one destroyed, so there is no downtime: Terraform always minimises disruption. The default order is destroy-then-create, printed as -/+; +/- appears only when create_before_destroy = true is set.
  4. The old instance is destroyed first, then a new one is created from the new AMI (default replacement order), then the record is updated to the new IP. web.example.com is down from the destroy until the new instance is up and the old DNS answer has expired. -/+ is destroy-then-create; dependents are updated only after the replacement's attributes are known, so there is an outage window.
In short

Terraform destroys the old instance first, then creates the new one, then updates the DNS record, so the site is down in between.

Why

Read the symbols before the attributes: -/+ says the object is replaced, and the # forces replacement comment names the argument the provider cannot update in place. The summary line counts a replacement as one add and one destroy. Because the default order is destroy-then-create, every dependent that reads an attribute of the replaced object (public_ip here) is updated after the new object exists, which is why the record is ~ with (known after apply). lifecycle { create_before_destroy = true } flips the order to +/- when the provider allows two objects to coexist (two instances can; two resources with the same unique name cannot), and Terraform propagates that setting to the resource's dependencies. The interview-grade answer names the outage window and the mechanism that removes it.

The common mistake

Assuming Terraform builds the replacement first. The default is destroy-then-create; +/- appears only when create_before_destroy = true is set and the provider lets two objects coexist.

4 Pick the strongest answer

Your root module has two provider configurations:

provider "aws" { region = "us-east-1" }
provider "aws" { alias = "west", region = "us-west-2" }

A shared child module, modules/replica, puts provider = aws.west on its resources, and the root calls it with just module "replica" { source = "./modules/replica" }. What happens when you run plan?

  1. It works, but the resources are silently created in us-east-1 because the child falls back to the default aws configuration. Terraform does not substitute a different configuration for a missing alias; it fails rather than deploy to the wrong region.
  2. Terraform errors: only the default (un-aliased) aws configuration is inherited implicitly. The child must declare configuration_aliases = [aws.west] in its required_providers, and the caller must pass providers = { aws.west = aws.west }. Implicit inheritance covers default configurations only; aliases are always explicit so a module's cross-region dependencies are visible at the call site.
  3. The fix is to add a provider "aws" { alias = "west" ... } block inside the child module. Provider blocks inside reusable modules are legacy: a module with its own provider configurations cannot use count, for_each, or depends_on, and removing the module later leaves Terraform with no configuration to destroy its resources.
  4. It works: a child module inherits every provider configuration in the root, aliases included. Only default provider configurations propagate into child modules; aliased ones never do.
In short

Terraform errors: aliased providers are never inherited, so the child must declare configuration_aliases and the caller must pass a providers map.

Why

Provider requirements (required_providers: source and version constraint) are declared per module, resolved once at init, and recorded in .terraform.lock.hcl. Provider configurations (provider blocks with region, credentials, aliases) belong to the root. A child module automatically receives the root's default configuration for each provider it requires; anything aliased must be requested by the child (configuration_aliases) and supplied by the caller (providers = { aws.west = aws.west }), which also lets a caller wire the child's aws.west to whatever configuration it chooses. Declaring provider blocks inside a shared module is the anti-pattern interviewers probe: it works until someone adds count to the module call, or removes the module and finds Terraform cannot destroy the orphaned resources because their provider configuration vanished with the block.

Read the docs

5 Find what's broken

This module came in as a take-home and is meant to be called from several AWS accounts. You have the reviewer's seat: which three lines do you mark, and what does each become?

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
    }
  }
}

variable "services" {
  type    = list(string)
  default = ["api", "worker", "web"]
}

variable "kms_key_arn" {
  type    = string
  default = "arn:aws:kms:us-east-1:123456789012:key/3f4e5d6c-7b8a-4901-a2b3-c4d5e6f70819"
}

resource "aws_ecr_repository" "svc" {
  count                = length(var.services)
  name                 = var.services[count.index]
  image_tag_mutability = "IMMUTABLE"

  encryption_configuration {
    encryption_type = "KMS"
    kms_key         = var.kms_key_arn
  }
}

resource "aws_ecr_lifecycle_policy" "expire_untagged" {
  count      = length(var.services)
  repository = aws_ecr_repository.svc[count.index].name
  policy     = file("${path.module}/lifecycle.json")
}

output "repository_urls" {
  value = aws_ecr_repository.svc[*].repository_url
}
In short

The three faults are the provider with no version pin (line 4), the hard-coded KMS key ARN default (line 16), and count over a list of names (line 20).

What's broken
  • Line 4: Provider required without a version constraint: every fresh init resolves the newest release, so plans differ between laptops and CI and can break on a major upgrade.
  • Line 16: An account- and region-specific KMS key ARN baked in as a variable default: the module silently points every caller at one account's key.
  • Line 20: count over a list of names: instances are addressed by position, so removing worker re-addresses web from [2] to [1], which is a rename, which forces replacement of the repository.
Why

The three things a startup reviewer looks for before reading a single resource argument are reproducibility (pinned providers and a committed lock file), portability (no ids or ARNs from one account hard-coded; data sources or required inputs instead), and stable addressing (for_each keyed by something a human chose, so a list edit cannot cascade into replacements). Line 10 is correct typing, line 22 is a good default (immutable tags stop a tag from being silently overwritten), and line 33 is the right way to ship a file with a module (path.module, not a path relative to the caller's working directory). The count fault is not cosmetic: name on an ECR repository forces replacement, so a list edit destroys registries.

6 Pick the strongest answer

Your production aws_rds_cluster carries lifecycle { prevent_destroy = true } and the team treats that as the guard. I am asking whether that is enough: which of these actually gets past it and deletes the cluster?

  1. None of them: once set, the flag is recorded in state and blocks every path until it is flipped to false and applied. lifecycle settings are configuration, not state; Terraform reads them from the current code on every plan.
  2. terraform destroy: the flag only guards against accidental replacement, not a deliberate destroy command. prevent_destroy makes any plan that includes destroying the resource fail with an error, including the plan produced by terraform destroy.
  3. Deleting the entire resource block from the configuration and running terraform apply: the lifecycle block disappears with it, so the plan shows an ordinary destroy. prevent_destroy is evaluated from configuration at plan time; once the block is gone there is nothing left to object, and an undeclared resource that is still in state plans as a destroy.
  4. Changing a force-new argument: a replacement (-/+) is not a destroy. A replacement is a destroy followed by a create; the plan is rejected with 'Instance cannot be destroyed'.
In short

Deleting the whole resource block removes the guard with it, so the next apply destroys the cluster.

Why

prevent_destroy is a plan-time assertion made by the configuration: "if this plan would destroy me, fail". It stops terraform destroy, replacement caused by a force-new change, and a careless -target. It cannot protect against the configuration that carries it being deleted, and terraform state rm sidesteps it by orphaning the object rather than destroying it. That is why a reviewer pairs it with a guard the API enforces regardless of Terraform (deletion_protection = true on RDS, force_destroy = false on S3) and with a CI gate that flags any planned destroy of a protected resource type. removed blocks (Terraform 1.7+) cover the legitimate case: stop managing the resource without destroying it.

Read the docs

7 Scenario: what do you do next?

A CI terraform apply for the payments-network root module was killed by the runner's 20-minute job timeout while it was waiting for a NAT gateway to become available. The next pipeline run's plan shows + aws_nat_gateway.main and + aws_route.private_default (Plan: 2 to add, 0 to change, 0 to destroy). In the AWS console a NAT gateway tagged Name=payments-nat, state available, already exists in the target subnet with an Elastic IP attached. Nothing is on fire yet; the private route does not exist.

Step 1. You own the next step. What do you do before anything else?

  1. Run terraform apply -refresh-only so state picks up the NAT gateway. Refresh re-reads objects that are already in state; it cannot discover an object Terraform never recorded.
  2. Delete the NAT gateway in the console so the plan matches reality. Destroys a working object and its EIP to satisfy a plan; import is the non-destructive way to reconcile state with reality.
  3. Check whether the object exists but is missing from state: terraform state list | grep nat_gateway, then aws ec2 describe-nat-gateways --filter Name=vpc-id,Values=<vpc> and compare ids. Plan says + create because state has no record, not because the object is absent; you must know which before applying anything.
  4. Approve the apply: it only adds resources, so it cannot break anything. It would create a second NAT gateway and allocate a second Elastic IP; 'only adds' is not 'harmless' when the real object already exists.

Step 2. state list shows no aws_nat_gateway.main. The CLI shows exactly one NAT gateway, nat-0b6d..., tagged payments-nat, in the right subnet with the EIP the configuration expects. What now?

  1. Add lifecycle { ignore_changes = all } to the resource so Terraform stops trying to create it. ignore_changes filters diffs on a tracked object; it has no effect on an object that is not in state.
  2. Bind it: terraform import aws_nat_gateway.main nat-0b6d... (or an import block), then re-plan and expect that resource to be a no-op; if it shows diffs, reconcile the configuration to the real object before applying anything. Import writes the object's identity into state without touching it; a clean plan afterwards is the proof that configuration and reality agree.
  3. Hand-edit terraform.tfstate to add the resource with its id. State is a versioned document with serial and lineage under a lock; hand edits bypass both and are easy to get subtly wrong. Import exists for exactly this.
  4. Rename the resource to aws_nat_gateway.main_v2 and apply so the address conflict goes away. There is no state under the new address either; Terraform creates a second gateway.

Step 3. Import done, the plan shows only + aws_route.private_default, you apply and the network is complete. The postmortem asks for a systemic fix. Which do you propose?

  1. Treat an interrupted apply as an incident with a mechanism behind it: apply-job timeouts longer than the slowest resource, alerts on non-zero apply exits, and a runbook step that reconciles state list against tagged cloud inventory before the next plan is approved. Addresses the mechanism (state is written per resource as the provider returns, so a kill mid-wait orphans the in-flight object) and makes the phantom create a detected condition rather than luck.
  2. Add -auto-approve to CI so applies finish faster. Removes review and changes nothing about how long a NAT gateway takes to become available.
  3. Set create_before_destroy = true on every resource in the module. Changes replacement order; it has nothing to do with a create that was never recorded.
  4. Ask engineers to run production applies from their laptops where they can watch them finish. Loses audit trail and locking discipline; a laptop lid closing orphans the object exactly the same way.
In short

First check state and AWS to see if the NAT gateway exists but is missing from state, then import it and expect a no-op plan.

Why

Terraform records a resource in state when the provider returns from creating it. A NAT gateway create issues the API call and then waits for available; kill the process during that wait and the object exists with no state entry, so the next plan proposes to create it again. The shape interviewers score: recognise that + means "not in state", not "does not exist"; reach for import rather than console deletes or state surgery; demand a no-op plan as verification; and propose a detection mechanism, not a reminder to be careful.

The common mistake

Approving because 'it only adds resources'. A second NAT gateway and a second Elastic IP are exactly what that apply creates.

Read the docs

8 Quick recall

Your plan shows -/+ on a certificate that is in use. What one lifecycle setting makes Terraform build the new object before it destroys the old one?

In short

The answer is create_before_destroy = true in a lifecycle block.

Accepted

create_before_destroy · Create_Before_Destroy · CREATE_BEFORE_DESTROY

Why

The default replacement order is destroy-then-create (-/+); create_before_destroy = true flips it to +/-, which only works when two objects may coexist, and Terraform propagates the setting to the resource's dependencies.

Read the docs

Next lesson Terraform in operation: remote state, drift, import, moved, workspaces, blast radius
Drill · Terraform core
0:00

Loading…