Module 2 closed with one piece flagged and left unopened: that terraform.tfstate file sitting on your laptop, in plain text, with no backup and with nothing stopping two people writing to it at the same time. You have run dozens of plan and apply operations trusting it without ever looking it in the eye. This module puts it centre stage, and this first lesson answers the underlying question: why it exists at all. Because state is not an implementation detail, nor a cache you can cheerfully delete: it is Terraform's memory, the only thing connecting your code to the real objects EcoMarket has deployed. Understanding what it stores, what it does not store and how it drifts away from reality is the difference between operating with confidence and operating with fear.

  1. The problem state solves

Imagine for a moment that Terraform had no state. You write this:

resource "local_file" "inventory" {
  filename = "${path.module}/${local.prefix}-inventory.json"
  content  = jsonencode({ project = "ecomarket" })
}

You run terraform apply. The file is created. The next day you run terraform apply again. Without state, Terraform faces three questions it could not answer:

  1. Does that file already exist because I created it, or because somebody else created it by hand? If somebody else created it, taking it under management means adopting something that is not yours without permission.
  2. If you change filename, should a new one be created and the old one deleted, or should it be renamed? Without remembering what the previous name was, the old file would be orphaned forever.
  3. If you delete the block from the .tf, what is there to destroy? A resource that is no longer in the code is invisible to Terraform: if it does not remember it, it cannot remove it.

You might think it is enough to ask the API: "give me every file in this directory", "give me every instance in this AWS account". That is the approach some tools take, and it has two serious problems:

  • Not everything is queryable or taggable. Many providers do not let you list resources by an arbitrary criterion, and others do not support tags to lean on.
  • It does not tell yours apart from other people's. In a shared account, listing "every database" also returns the data team's, the backup vendor's and the ones somebody created in 2019. Terraform would destroy things it does not manage.

State answers all three questions with an explicit record: this is what I created, with this identifier, and this is how it looked the last time I checked.

  1. The three worlds: configuration, state and infrastructure

The most useful way to think about Terraform is as an engine comparing three different worlds:

flowchart LR
    A["CONFIGURATION<br/>.tf files<br/><i>what you want</i>"]
    B["STATE<br/>terraform.tfstate<br/><i>what Terraform remembers</i>"]
    C["INFRASTRUCTURE<br/>the provider's real API<br/><i>what actually exists</i>"]

    B -- "refresh: read reality" --> C
    C -- "updates the state" --> B
    A -- "comparison: plan" --> B
    B -- "actions: apply" --> C

    style A fill:#e8f4ff,stroke:#2b6cb0
    style B fill:#fff6e5,stroke:#b7791f
    style C fill:#e9f7ef,stroke:#2f855a

A plan is exactly that: refresh the state against reality, then compare the configuration with the refreshed state. The differences between those three worlds each have their own name:

Difference Situation What Terraform does
Configuration ≠ state You changed the .tf Proposes creating, modifying or destroying
State ≠ infrastructure Somebody touched the console Drift: detected on refresh
Configuration ≠ infrastructure, state empty Resource created outside Terraform It cannot see it; it has to be imported (06-04)
State holds something that is neither in the configuration nor in reality Somebody deleted it by hand Proposes creating it again

The three worlds also explain why state is dangerous: if you lose it, Terraform forgets that it created EcoMarket's production database and, on the next apply, will propose creating another one. If you manipulate it badly, it will propose destroying what it should not.

  1. What state stores exactly, and what it does not

State is a JSON document. Its anatomy field by field is the subject of the next lesson, State Files; what matters here is the conceptual content.

It does store:

Element What it is for
Each resource's address (local_file.inventory) Identifying the configuration block that manages it
The object's real identifier (id) Knowing which provider object it corresponds to
Every attribute as it stood after the last apply Comparing and detecting changes without calling the API
The provider that manages it Knowing which plugin to ask for CRUD operations
The dependencies between resources Ordering creation and, above all, destruction
The output values (outputs) Serving terraform output and shared remote state
Metadata: serial, lineage, terraform_version Detecting conflicting writes and mixed-up states

It does not store:

  • The configuration itself. State does not contain your expressions, your locals, your for_each or your comments. It stores the result of evaluating them. That is why you cannot reconstruct the .tf from the state.
  • The values of input variables. A var.db_password does not appear as a variable; it appears, if at all, embedded in the attribute of the resource that used it.
  • Provider binaries. Those live in .terraform/, which genuinely is a disposable cache.
  • A history. State is a snapshot of the last apply, not a change log. Versioning comes from the backend (that is, the bucket), not from Terraform.
  • Whatever it does not manage. Resources created by hand are invisible until they are imported.

One practical consequence: state is not a backup of your infrastructure. It contains neither database rows nor bucket files. Restoring a state restores nothing real; it only restores Terraform's memory.

  1. State as a map of identities

This is state's most important role, and the one that justifies everything else. When you write:

resource "local_file" "inventory" {
  filename = "${path.module}/ecomarket-dev-inventory.json"
  content  = jsonencode({ project = "ecomarket" })
}

the address local_file.inventory is a name you made up. The local provider knows nothing about it: as far as the file system is concerned, there is only a path. The correspondence between the two lives exclusively in the state:

{
  "mode": "managed",
  "type": "local_file",
  "name": "inventory",
  "provider": "provider[\"registry.terraform.io/hashicorp/local\"]",
  "instances": [
    {
      "attributes": {
        "id": "b5d31e8ff1b48a1f7c9e2d0a3f6b81c4d9e0a2f7",
        "filename": "./ecomarket-dev-inventory.json",
        "content": "{\"project\":\"ecomarket\"}"
      }
    }
  ]
}

The id field is the identifier the provider returns. Here it is a SHA-1 hash of the content; in AWS it would be i-0a1b2c3d4e5f67890 for an instance, ecomarket-prod-images-9f3a2b1c for a bucket, ecomarket-prod-db for an RDS database. It is the only way Terraform has of finding the object again.

Three consequences follow, and they are worth internalising now:

  1. If you change the address in the code, Terraform loses the correspondence. local_file.inventory renamed to local_file.general_inventory is, as far as the state is concerned, one resource disappearing and another being born: destroy + create. That problem has a declarative solution, and it is the subject of Declarative Refactoring.
  2. If somebody deletes the real object, the id in the state points at nothing. Terraform will detect it on refresh and propose recreating it.
  3. If you copy the state from dev to prod, you are saying that the production objects are the development ones. On the next apply, Terraform "corrects" production until it looks like development. It is one of the most expensive accidents there is.

  1. Recorded dependencies and why destroy needs them

In module 1 you saw the dependency graph: Terraform deduces from your references that local_file.inventory depends on random_pet.suffix, and that is why it creates the second one before the first. But the graph is computed from the configuration. What happens when the configuration is no longer there?

That is exactly the case with terraform destroy on resources you have just deleted from the code: there are no references left to analyse. That is why the state stores a dependencies list on each instance:

{
  "type": "local_file",
  "name": "inventory",
  "instances": [
    {
      "attributes": { "id": "b5d31e8f..." },
      "dependencies": [
        "random_id.suffix_hex",
        "random_pet.suffix"
      ]
    }
  ]
}

With that list, Terraform can order the destruction in reverse even though the code has vanished: the inventory first, then the suffixes. In a real EcoMarket infrastructure the order matters enormously: you cannot delete the subnet before the instance living in it, nor the security group before whatever references it. The API would return a dependency error and leave your destroy half-finished.

flowchart TB
    subgraph CREATE["apply: creation order"]
        direction LR
        A1["random_pet.suffix"] --> A2["local_file.inventory"]
    end

    subgraph DESTROY["destroy: reverse order, read from the state"]
        direction LR
        B1["local_file.inventory"] --> B2["random_pet.suffix"]
    end

    CREATE -.-> DESTROY

Operational corollary: if you edit the state by hand and remove the dependencies, the destroy can fail or leave orphaned resources. It is one of the reasons state is not edited by hand.

  1. Performance: state as a cache and the role of refreshing

There is a second justification for state, less elegant but very real: speed.

Every plan needs to know how the infrastructure looks right now. In theory it would be enough to query the API for each resource. In a small configuration that is instantaneous. In EcoMarket's production infrastructure — dozens of resources across network, compute, database, load balancer, buckets, DNS and certificates — that is dozens of HTTP calls, each with its latency, its rate limit and its chance of failing.

Terraform mitigates this in two ways:

  • It parallelises the refresh (by default, up to 10 concurrent operations; tunable with -parallelism=N).
  • It caches the attributes in the state, so that comparing content does not require re-reading the file if you already know what was there.

And it gives you the option of skipping the refresh entirely:

# Plan without querying reality: compares the configuration against the state as it is.
$ terraform plan -refresh=false

This is faster, but it assumes the state is faithful. That is acceptable in a pipeline that applied two minutes ago, or when the provider's API is degraded and you need to see the change in your code. It is dangerous as a habit, because any drift goes unnoticed.

Option Queries the API Modifies the state Typical use
terraform plan Yes No (in memory) Day-to-day work
terraform plan -refresh=false No No Fast iteration, degraded API
terraform plan -refresh-only Yes No Auditing drift
terraform apply -refresh-only Yes Yes Accepting drift into the state
terraform apply Yes Yes Full convergence

  1. What happens to state at each phase of plan and apply

It is worth having the timeline clear, because it explains a lot of apparently odd behaviour.

During terraform plan:

  1. Terraform reads the state (from the local file or the remote backend).
  2. It acquires a lock if the backend supports one — plan locks too, because it refreshes. That is the subject of State Locking.
  3. It refreshes: for each resource in the state, it calls the provider's Read with the stored id and obtains the current attributes. This happens in memory; the file is not touched.
  4. It evaluates the configuration, resolving variables, locals, data sources and expressions.
  5. It compares the configuration against the refreshed state and produces the plan.
  6. It releases the lock. The state file has not changed.

An important nuance: since Terraform 0.15.4, the refresh in a plan does not write the state. In very old versions it did, and that is where the confusion in a lot of outdated documentation comes from.

During terraform apply:

  1. It reads the state and acquires the lock (a write lock this time, held for the whole operation).
  2. It refreshes and recalculates the plan, unless you pass it a saved plan file from -out.
  3. It executes the actions in graph order.
  4. It writes the state after each resource, not at the end. If the apply is interrupted halfway through, whatever has been created is already recorded.
  5. It updates serial, writes terraform.tfstate.backup with the previous version and releases the lock.

Point 4 is the key to understanding why a Ctrl+C halfway through an apply is usually not catastrophic: Terraform tries to finish the operation in flight and save. What is catastrophic is killing the process with kill -9 right as it is writing.

  1. Drift: when reality goes off script

Drift is any difference between what the state remembers and what really exists. It happens because infrastructure has more than one actor.

The canonical EcoMarket case: it is Friday afternoon, the site is slow, and somebody with console access raises the instance count of ecomarket-prod-web from 2 to 4 "just while the peak lasts". Nobody touches the repository. On Monday, a different person runs terraform apply to deploy a minor configuration change... and the plan proposes dropping from 4 instances to 2 in the middle of rush hour.

Common sources of drift, in order of frequency:

Source EcoMarket example Severity
Manual change in the console or CLI Scaling the web tier on a Friday High: lost on the next apply
Provider automation Autoscaling adjusts the instance count High unless ignore_changes is used
Another team with permissions Security adds a rule to the security group High
Provider default values The API fills in a field you did not specify Low: noise in the plan
Accidental deletion Somebody removes the staging images bucket Very high
Provider version change New attribute with a different default Medium

There is a distinction that avoids a lot of frights: not every difference is drift that needs correcting. Autoscaling changing the instance count is a legitimate and expected change; the right answer is not "restore the value from the code" but to declare that Terraform does not manage that attribute:

resource "aws_autoscaling_group" "web" {
  name             = "${local.prefix}-web"
  min_size         = local.current.web_instances
  max_size         = local.current.web_instances * 3
  desired_capacity = local.current.web_instances

  lifecycle {
    # Autoscaling manages this value live. If Terraform tried to
    # "correct" it every Monday, it would cut capacity at peak time.
    ignore_changes = [desired_capacity]
  }
}

(lifecycle and ignore_changes were covered in Resource and Data Blocks; here we only point out their role as an antidote to legitimate drift.)

  1. Detecting drift: plan, -refresh-only and apply -refresh-only

9.1. With terraform plan

A normal plan already detects drift, because it refreshes before comparing. Terraform shows it in a section of its own, before the plan of changes. Let us provoke it with EcoMarket's local_file, which is runnable on your own machine:

# Somebody "fixes" the inventory by hand, like touching the console on a Friday.
$ echo '{"project":"ecomarket","patched_by_hand":true}' > ecomarket-dev-inventory.json

$ terraform plan
Note: Objects have changed outside of Terraform

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

  # local_file.inventory has been deleted
  - resource "local_file" "inventory" {
      - id       = "b5d31e8ff1b48a1f7c9e2d0a3f6b81c4d9e0a2f7" -> null
      - filename = "./ecomarket-dev-inventory.json" -> null
    }

Terraform will perform the following actions:

  # local_file.inventory will be created
  + resource "local_file" "inventory" {
      + content  = jsonencode({ project = "ecomarket" })
      + filename = "./ecomarket-dev-inventory.json"
      + id       = (known after apply)
    }

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

Two things to explain carefully:

  • The local provider identifies the file by the hash of its content. Once the content changes, the stored id no longer corresponds to anything, so the refresh concludes that the object has gone (has been deleted). A cloud provider, with stable identifiers, would say has changed and show it attribute by attribute.
  • The Note: Objects have changed outside of Terraform section is informational: it tells you what the refresh found. The Terraform will perform the following actions block is what is going to be done. Do not confuse them: the first has already happened, the second is yet to happen.

9.2. With terraform plan -refresh-only

When what you want is to audit drift without mixing it up with the pending changes in your code, there is refresh-only mode:

$ terraform plan -refresh-only
local_file.inventory: Refreshing state... [id=b5d31e8ff1b48a1f7c9e2d0a3f6b81c4d9e0a2f7]

Terraform will perform the following actions:

  # local_file.inventory has been deleted
  - resource "local_file" "inventory" {
      - id       = "b5d31e8ff1b48a1f7c9e2d0a3f6b81c4d9e0a2f7" -> null
      - filename = "./ecomarket-dev-inventory.json" -> null
    }

This is a refresh-only plan, so Terraform will not take any actions to undo
these. If you were expecting these changes then you can apply this plan to
record the updated values in the Terraform state without changing any remote
objects.

This mode ignores the configuration entirely: it proposes creating nothing and modifying nothing. It only says "this is what the real world has and your state does not know about". It is the auditing tool: a terraform plan -refresh-only -detailed-exitcode scheduled every night on prod is a cheap and effective way of finding out about manual changes the next day rather than the next month.

# In a nightly audit pipeline:
#   0 = no drift, 1 = error, 2 = drift found
$ terraform plan -refresh-only -detailed-exitcode
$ echo $?
2

9.3. With terraform apply -refresh-only

If you decide that reality is right and the state should adapt, you apply the refresh-only plan:

$ terraform apply -refresh-only
Would you like to update the Terraform state to reflect these detected changes?
  Terraform will write these changes to the state without modifying any real
  infrastructure.

  Enter a value: yes

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Look at the summary: 0 added, 0 changed, 0 destroyed. Nothing real has been touched; only Terraform's memory has been updated. It is the safest operation there is on infrastructure, and it is the modern replacement for the old terraform refresh, which did the same thing but without asking or showing you anything. That is why terraform refresh is marked as deprecated: it changed the state blind.

  1. Resolving drift: four strategies

Once drift has been detected, there are exactly four reasonable responses. Choosing badly is what turns a small incident into a large one.

Strategy Command When Effect
Revert: the code wins terraform apply The manual change was a mistake or a bodge Reality goes back to what is declared
Adopt: reality wins Edit the .tf and terraform apply The manual change was right and should stick The code reflects what is there; clean plan
Record: reality wins, without touching the code terraform apply -refresh-only Attributes Terraform should not govern The state is synchronised; it may reappear in the next plan
Ignore: declared out of management lifecycle { ignore_changes = [...] } Attributes managed by other automation Terraform stops proposing changes to them

Applied to EcoMarket's Friday:

  1. Monday morning, before anything else: terraform plan -refresh-only on prod to see all the accumulated drift.
  2. Check with the person who scaled the web tier whether it is still necessary.
  3. If the traffic has settled at the new level, adopt it: raise web_instances from 2 to 4 in prod.tfvars, open a PR, review it and apply. The change is then documented in the Git history, which is where it belongs.
  4. If it was a one-off, revert it with a normal apply, but in a maintenance window, not at 11 in the morning.
  5. And open a background task: restrict console write permissions on prod so that next Friday it cannot happen again. The best drift management is the kind that stops drift happening.

  1. Inspecting state: state list, state show and show

State is queried with commands, not by opening the JSON. The three essentials:

# 1. Inventory of managed addresses: the bird's-eye view.
$ terraform state list
local_file.inventory
random_id.suffix_hex
random_pet.suffix
# 2. Every attribute of ONE resource, in readable HCL format.
$ terraform state show random_pet.suffix
# random_pet.suffix:
resource "random_pet" "suffix" {
    id        = "cheerful-mammoth"
    keepers   = {
        "environment" = "dev"
    }
    length    = 2
    separator = "-"
}
# 3. The COMPLETE state, outputs included.
$ terraform show

# 4. The same content, in JSON, to process with jq.
$ terraform show -json | jq -r '.values.root_module.resources[].address'
local_file.inventory
random_id.suffix_hex
random_pet.suffix

Differences worth being clear about:

Command Scope Format Refreshes
terraform state list Addresses only Plain text No
terraform state show ADDR One resource, all its attributes Readable HCL No
terraform show Full state + outputs Readable HCL No
terraform show -json Full state Stable, documented JSON No
terraform show plan.tfplan A saved plan Readable HCL No

terraform show -json versus reading the .tfstate with jq. The state file is an internal format that HashiCorp may change; the output of terraform show -json is a documented and stable format. For scripts and audits, always use show -json.

The full repertoire of terraform state — including the commands that modify the state, such as mv, rm or push — is the subject of the next lesson.

  1. Local state versus remote state: the big picture

By default, state lives in ./terraform.tfstate, next to your code. That is exactly what EcoMarket has right now, and it is no good for a team:

Problem Consequence at EcoMarket
It cannot be shared If you apply and your colleague applies, each laptop believes it created the whole infrastructure
It is not durable One broken disk or one rm -rf of the directory and Terraform forgets production
It is not encrypted Anyone with access to the laptop reads the PostgreSQL password
It has no locking Two simultaneous apply runs corrupt the state
It is not reachable from CI A pipeline with no shared state cannot deploy

The solution is a remote backend: S3, Azure Blob, GCS, Terraform Cloud. State stops being a file of yours and becomes a shared object, versioned, encrypted and lockable. It is the module's decisive step, and it is developed in Remote State; the locking mechanism, in State Locking.

  1. Plain-text secrets inside the state

In Variables and Outputs you ran an uncomfortable demonstration: marking an output as sensitive = true hides it in the terminal, but the value is still in the state in plain text. Let us bring it back, because now it has a solution:

# The password you pass through TF_VAR_db_password and never write in a .tf...
$ export TF_VAR_db_password='an-example-password'
$ terraform apply -auto-approve

# ...is literally here:
$ jq -r '.outputs.db_connection_string.value' terraform.tfstate
postgresql://ecomarket_app:an-example-password@ecomarket-dev-db:5432/ecomarket

# And the state itself marks which attributes are "sensitive"... for the CLI,
# not for the disk:
$ jq '.resources[].instances[].sensitive_attributes' terraform.tfstate
[]

Why it happens, and why it is not a bug: Terraform needs the complete values in order to compare them in the next plan. A hash would not do: it could not compute the difference, nor pass the value to the provider. State is, by design, a document with production data inside it.

The operational conclusion is a hard one and has to be accepted: the state file carries the same security classification as the most sensitive secret it contains. If the prod PostgreSQL password is in there, the state is a production document of the highest criticality. Treat it as such, and agree the specific policy you apply with your security team.

There are three mitigation routes, and they are not alternatives: you use all three at once.

Route What it does Where it is developed
Encryption at rest and in transit The backend encrypts the object with KMS/SSE and serves it over TLS Remote State
Least-privilege access control Only the CI role and a small group read the prod state Remote State and Security
Not putting the secret in the state Generate the password in a secrets manager and reference it, rather than passing it through Terraform Security

The third is the only one that attacks the root of the problem, and also the hardest: some resources demand the password as an argument, and then it ends up in the state no matter what. What you can do is reduce the surface: do not create outputs containing secrets, do not store plan files (-out) as CI artefacts, and use automatic rotation from the secrets manager so that the value in the state expires quickly.

Security warning. Never upload a terraform.tfstate, a terraform.tfstate.backup or a *.tfplan file to Git, to a ticket, to a chat channel or to a pastebin to ask for help. They contain production data in plain text. If you need to share information to debug, use terraform state list or a hand-redacted version of strictly what is needed.

Common Mistakes and Tips

  • Treating the state as a disposable cache. .terraform/ can be deleted without risk; terraform.tfstate cannot. The similarity of the names has cost entire production environments.
  • Always running with -refresh=false because "it is faster". It works right up until the day somebody touched the console and your plan applies against a reality that no longer exists.
  • Confusing the "Objects have changed outside of Terraform" section with the plan. The first describes the past; the second, the future. Read them separately.
  • Using terraform refresh. It is deprecated because it modifies the state without showing you first what is going to change. Use terraform apply -refresh-only, which does ask for confirmation.
  • Answering every drift with an immediate apply. Before reverting, ask why somebody changed it. Sometimes the manual change was saving the service.
  • Copying terraform.tfstate from one environment to another "to get started quickly". You are telling Terraform that the prod objects are the dev ones. The next apply will do real damage.
  • Tip: schedule a nightly terraform plan -refresh-only -detailed-exitcode per environment and notify the team channel when it returns 2. Detecting drift in 24 hours instead of in 3 months changes the conversation completely.
  • Tip: add terraform state list at the start of any debugging session. Knowing what you manage is the first step of every diagnosis.
  • Tip: before any delicate operation on the state, take a copy: cp terraform.tfstate state-$(date +%Y%m%d-%H%M).json locally, or download a version from the bucket if you are already remote.

Exercises

Work in a fresh directory with EcoMarket's module 1 configuration (the local and random providers, the local_file.inventory resource and the two random suffixes). Everything is runnable without any cloud account.

Exercise 1: provoke, audit and resolve drift

  1. Apply the configuration and note down the id of local_file.inventory with terraform state show.
  2. Edit the generated file by hand, adding a "patched_by_hand": true key.
  3. Run terraform plan -refresh-only and explain what it tells you and what it does not tell you.
  4. Run a normal terraform plan and point out the two distinct sections of the output.
  5. Decide: which command would you run if the manual patch was correct and should stick? And if it was a mistake? Justify both answers.
  6. Resolve the drift by reverting it and check with terraform state show that the id matches the declared content again.

Exercise 2: state as a map of identities

  1. With the infrastructure applied, run terraform state list and terraform show -json | jq '.values.root_module.resources[] | {address, type, values: {id: .values.id}}'.
  2. Rename local_file.inventory to local_file.general_inventory in the code (just the block label, nothing else) and run terraform plan without applying. Note down the summary.
  3. Explain why Terraform proposes that, in terms of the map of identities.
  4. Undo the rename and check that the plan is clean again.

Exercise 3: what is really inside the state

  1. Add a random_password.db resource of 20 characters to the configuration, plus an output generated_password marked as sensitive = true.
  2. Apply and run terraform output generated_password. What do you see?
  3. Look for the value inside terraform.tfstate with jq. What do you see now?
  4. Run jq '.resources[] | select(.type=="random_password") | .instances[0].sensitive_attributes' terraform.tfstate and explain what that field is for and what it is not for.
  5. Write, in three lines, the policy you would propose to EcoMarket for this file.

Solutions

Solution 1:

$ terraform apply -auto-approve
$ terraform state show local_file.inventory | grep '^    id'
    id = "b5d31e8ff1b48a1f7c9e2d0a3f6b81c4d9e0a2f7"

$ python3 -c "import json;d=json.load(open('ecomarket-dev-inventory.json'));d['patched_by_hand']=True;json.dump(d,open('ecomarket-dev-inventory.json','w'))"

In point 3, terraform plan -refresh-only reports that the object has changed with respect to the state, and proposes no action on reality: it only offers to update the state. What it does not tell you is whether your configuration is up to date; it ignores the .tf entirely.

In point 4, the normal plan shows two sections: Note: Objects have changed outside of Terraform (drift that has already happened) and Terraform will perform the following actions (what it will do to converge, here recreating the file).

Point 5:

Scenario Command Why
The patch was correct Edit the .tf so that it generates that content + terraform apply The code has to be the source of truth; adopting the change documents it in Git
The patch was a mistake terraform apply without touching the code The configuration wins and reality goes back to what is declared

Note: in this particular case, apply -refresh-only would not work for "adopting" the change, because the file's content is determined by the configuration; the next plan would propose the correction again. Recording drift in the state only makes sense for attributes the code does not govern.

Solution 2:

$ terraform plan
  # local_file.inventory will be destroyed
  # (because local_file.inventory is not in configuration)
  - resource "local_file" "inventory" { ... }

  # local_file.general_inventory will be created
  + resource "local_file" "general_inventory" { ... }

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

The explanation: the state indexes objects by address, not by content or by file name. local_file.inventory and local_file.general_inventory are two different addresses; as far as the state is concerned, the first has disappeared from the configuration (it must be destroyed) and the second is new (it must be created). The fact that both point at the same path on disk is irrelevant to Terraform.

This is precisely what the moved block solves, which you will see in Declarative Refactoring.

Solution 3:

resource "random_password" "db" {
  length  = 20
  special = true
}

output "generated_password" {
  description = "Generated password for PostgreSQL. Example only."
  value       = random_password.db.result
  sensitive   = true
}
# Point 2: the CLI protects it.
$ terraform output generated_password
<sensitive>

# Point 3: the disk does not.
$ jq -r '.resources[] | select(.type=="random_password") | .instances[0].attributes.result' terraform.tfstate
xR7#mQ2vLp9$Kd4aZt1B

# Point 4:
$ jq '.resources[] | select(.type=="random_password") | .instances[0].sensitive_attributes' terraform.tfstate
[
  {
    "type": "get_attr",
    "value": "result"
  }
]

sensitive_attributes is a list of attribute paths that Terraform must hide when printing plans and outputs. Its purpose is to stop the CLI leaking the value on screen or in the logs. It does not serve to encrypt it, nor to omit it from the file, nor to restrict who can read it: the value is right there, in plain text, two lines further up in the same JSON.

Point 5, the policy proposed for EcoMarket:

  1. State is never versioned or shared: terraform.tfstate* and *.tfplan in .gitignore, no exceptions, and never attached to tickets.
  2. State lives in a remote backend with encryption at rest (KMS), TLS in transit, versioning enabled and per-environment restricted access: only the CI role writes to prod.
  3. Passwords are generated and rotated in a secrets manager; Terraform references them instead of creating them, and no output containing them is published. This policy is reviewed by the security team before it is applied.

Conclusion

State stops being a mysterious file as soon as you understand its role:

  • Terraform compares three worlds: the configuration (what you want), the state (what it remembers) and the infrastructure (what exists). A plan refreshes the second against the third and compares it with the first.
  • State is the map of identities between your addresses (local_file.inventory) and the provider's real identifiers. Changing the address breaks the correspondence; losing the state is the same as Terraform forgetting what it created.
  • It also stores the dependencies, and that is why it can destroy in reverse order even when the code is gone; and it caches attributes, which is what makes a plan over dozens of resources viable.
  • During a plan, the refresh happens in memory and the file is not touched; during an apply, the state is written after each resource.
  • Drift is the difference between the state and reality. It is detected with terraform plan, audited in isolation with plan -refresh-only and recorded with apply -refresh-only (the replacement for the deprecated terraform refresh). It is resolved by reverting, adopting, recording or ignoring: four responses, and choosing well matters more than being fast.
  • It is inspected with terraform state list, state show and show -json, which is the stable format for automation.
  • And it contains plain-text secrets, by design, which makes it a document as critical as whatever it holds inside.

You now know what state is for and how it behaves. What you have not done yet is open it and really read it: what each field of the JSON means, when terraform.tfstate.backup appears, and what you can do to it with the terraform state commands without breaking anything. That is exactly State Files, the next lesson, where you will also learn to move, rename and stop managing resources — and to tell the reversible operations from the ones that are not.

© Copyright 2026. All rights reserved