Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Understanding the Terraform state: role, content, secrets and drift

14 min read
Improve this page

Logo Terraform

The Terraform state is the file that links your code to the real world. Without it, Terraform no longer knows which resources it manages and tries to recreate everything. It is more than a mapping table: the state stores secrets in plain text, it only reveals drift (a change made outside Terraform) if Terraform has reread the real world just before, and it protects itself against some overwrites with two fields, serial and lineage. These are the three traps of this guide.

Tested on Debian 13 with Terraform v1.15.4, the hashicorp/random 3.9.1 and hashicorp/local 2.9.1 providers, jq 1.7 and a local state.

What you will learn

  • Name the three roles of the state: mapping, dependencies, cache
  • Read the content of the state, serial and lineage included
  • Check that sensitive masks the display but leaves the secret in plain text
  • Explain why drift only shows up after a refresh
  • Use the terraform state commands and the state push safeguards
  • Adopt an existing resource with an import block and keep the state out of Git

What the state is for: three roles, not one

The official documentation gives the state three roles:

  1. Mapping: associate each address (random_password.db) with the real object.
  2. Metadata: remember the dependencies between resources. This is what gives the destruction order when a resource has already disappeared from the code, "the order cannot be determined from the configuration alone".
  3. Performance: the state works as an attribute cache. On a large infrastructure, -refresh=false and -target speed up operations, at the price of a state that may be stale.

What the state contains

The state is a JSON file named terraform.tfstate, in version: 4 format. To read it on a concrete case, create a test folder with this main.tf, which draws a random password and writes a configuration file:

terraform {
required_version = ">= 1.15.4"
required_providers {
random = {
source = "hashicorp/random"
version = "3.9.1"
}
local = {
source = "hashicorp/local"
version = "2.9.1"
}
}
}
resource "random_password" "db" {
length = 16
special = false
}
resource "local_file" "config" {
filename = "config.ini"
content = "db_host = 10.0.0.5\n"
}

Run terraform init, then terraform apply -auto-approve. The last line of the output reports the two resources created:

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

The header fields of the state are read with terraform state pull, which prints the full JSON, filtered here with jq:

Terminal window
terraform state pull | jq '{version, terraform_version, serial, lineage}'
{
"version": 4,
"terraform_version": "1.15.4",
"serial": 3,
"lineage": "89b1f3bc-734d-f688-5518-f95bbc8cc29e"
}

You can read the format (version), the Terraform version that wrote the file, the serial counter and the lineage identifier lineage. Your lineage will differ: Terraform draws it at random when the state is created. At the root, the file also holds outputs, resources and check_results. Each resource instance also holds schema_version, sensitive_attributes, dependencies and private.

  • serial is a counter of state writes, not of apply runs. Terraform rewrites the state several times per operation: on this two-resource configuration, the first apply leaves serial: 3, as above, and a following apply that changes one resource leaves serial: 6.
  • lineage is the UUID of the state's lineage. It acts as a safeguard for terraform state push (see below).

The terraform.tfstate.backup backup does not exist after the first apply. Terraform only creates it at the first rewrite of the state, and it then holds the previous serial (3 when the current one is 6).

The secret is in plain text in the state

Marking a value sensitive does not remove it from the state: "Terraform stores values with the sensitive argument in both state and plan files, and anyone who can access those files can access your sensitive values".

The diagram follows the password from your code to the state. Look at where it stays in plain text, and what a remote backend (encryption at rest, restricted access) changes: it protects the file, it does not remove the value from the state.

The password of random_password.db is drawn at creation and written in plain text in the state. The terminal only displays (sensitive value). A remote backend encrypted at rest limits access to the state, but anyone who can read it, through a copy, Git or overly broad access, reads the secret. Only ephemeral and write-only keep the value out of the state.     random_password.db     your code     terminal     (sensitive value)     state     result in plain text value drawnat creation  masked display      remote backend     encrypted at rest, limited access     whoever reads the state     copy, Git, broad access limits who can read  plain-text read      ephemeral · write-only     never written to the statethe secret lives hereComponentSecretControlThreatPreventionLegitimate flowHostile flowControl
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

With the main.tf above, terraform state show does mask the value:

Terminal window
terraform state show random_password.db
# random_password.db:
resource "random_password" "db" {
bcrypt_hash = (sensitive value)
id = "none"
length = 16
lower = true
min_lower = 0
min_numeric = 0
min_special = 0
min_upper = 0
number = true
numeric = true
result = (sensitive value)
special = false
upper = true
}

Look at the bcrypt_hash and result lines: they display (sensitive value). Yet the state itself holds the value. terraform state pull exports the full JSON, and jq extracts the password:

Terminal window
terraform state pull | jq '.resources[] | select(.type=="random_password") | .instances[0].attributes.result'
"zfELiMDCg4xvh0Hz"

The password comes out in plain text. This demonstration value was destroyed along with the test machine: yours will differ. Never run this command on a real project in front of a shared screen or in a CI job, whose logs are kept and read.

terraform state show therefore masks the value, while the state file holds it in plain text, as does terraform show -json. The same attribute appears in the sensitive_attributes of the instance: the mark exists, the protection does not. For how sensitive propagates between variables and outputs, and its limits, see sensitive in Terraform (in French).

Drift only shows up with a refresh

Terraform does not watch your infrastructure: it only sees drift (a change made outside Terraform) when it refreshes the state by rereading the real world, which a plan does by default. Detecting drift is part of the "Manage resource lifecycle" objective of the Terraform Professional certification (in French). Here is what Terraform 1.15.4 returns after a file managed by Terraform is changed outside it:

CommandExit codeWhat it proves
terraform plan -detailed-exitcode2the drift is seen (refresh)
terraform plan -refresh=false -detailed-exitcode0the state alone sees nothing

With -detailed-exitcode, plan returns 0 when there is nothing to do, 1 on error and 2 when changes are planned.

Detection therefore comes from the refresh, not from the state. A CI job that runs with -refresh=false to go faster can miss drift. To reconcile a drift that was seen and to adopt orphan objects, see diagnosing the state (in French).

To refresh without planning any change, terraform apply -refresh-only asks for confirmation before rewriting the state. The terraform refresh command is deprecated in favor of -refresh-only.

Reading and writing the state: the commands

You read and write the state only through the terraform state commands, never by editing the file:

CommandRole
state list, state showlist, inspect (show masks secrets)
state pull, state pushexport, import the full state
state mvrename a resource without destroying it
state rmremove a resource from the state (without destroying it)

state mv renames a resource without destroying it: after a mv, the plan is empty, whereas a simple rename in the code plans 1 resource to create and 1 to destroy. The declarative moved block is still preferable: it is written in the code, so it is versioned and reviewed, whereas a state mv is a one-off action that nobody else keeps a trace of.

Each command has its own lesson in this module: state list (in French), state show (in French), state mv (in French) and state rm (in French).

The safeguards: serial and lineage

The serial does not protect against two simultaneous operations: that role belongs to a lock set by the backend (Error acquiring the state lock), not to a comparison of serials. The serial safeguard lives elsewhere, on terraform state push:

  • pushing a state with a lower serial is refused: cannot import state with serial 3 over newer state with serial 6 (exit 1, current state untouched);
  • pushing a state with a different lineage is refused, with a distinct message: cannot import state with lineage "..." over unrelated state with lineage "...". This is the protection against overwriting with the state of another project.

Before forcing a state push, make a copy of the current state: the lesson backing up and restoring the state (in French) details these safeguards and how to roll back.

Locking is automatic on any operation that may write the state, even with the local backend. How it works, -lock=false and terraform force-unlock are covered in locking the state (in French).

Recovering a lost state: the import block

If the state is lost, Terraform wants to recreate everything. The first resort is to restore a backup, as explained in backing up and restoring the state (in French). Without a backup, you have to reattach the existing objects one by one. Rather than the terraform import command, which works line by line outside the code, use the declarative import block (Terraform 1.5+), applied by terraform apply and reviewed along with the rest of the configuration. For the password of the example, the random provider expects the password value itself as the identifier:

import {
to = random_password.db
id = "the-password-value-in-use"
}

The documentation of the hashicorp/random 3.9.1 provider states that attributes written in the configuration are ignored at import: the imported object receives the length of the value and the default values of the other attributes (special and lower are true). The special = false of the main.tf above differs from that: the next apply would replace the password. To take over a password without regenerating it, the resource declares only length, equal to its actual length. The terraform plan -generate-config-out=file.tf option can generate the configuration from the imported object. The import block and this generation are detailed in diagnosing the state (in French).

The .gitignore: what gets committed and what does not

The state is never committed. These three lines cover states, backups and workspace states:

*.tfstate
*.tfstate.*
.terraform/

Conversely, .terraform.lock.hcl must be versioned: it pins the provider versions for the whole team.

Put it into practice

The lab starts from a password that is already in service. A plain apply would draw a new one, which is not what you want for a secret the application uses, so you attach the existing one with an import block. You then check that the value is in plain text in the state even though the attribute is listed in sensitive_attributes. The masking is a display feature, not encryption. The validation checks that the password was not regenerated, that the secret is in plain text in the state, that plan sees drift with a refresh and not without one, and that state push refuses a lower serial and a different lineage.

Key takeaways

  • The state has three roles: mapping, dependencies, attribute cache.
  • serial counts writes, not apply runs; the backup only appears at the first rewrite.
  • A secret marked sensitive stays in plain text in the state; state show masks it, but the file and show -json reveal it. Only ephemeral and write-only arguments exclude it.
  • Drift is only detected with a refresh (plan = 2, -refresh=false = 0).
  • The safeguards live on state push: a lower serial and a different lineage are refused. Concurrency, on the other hand, is handled by the lock.

FAQ: frequently asked questions

The questions below cover the traps of the state: the secret you think is protected, the drift you think is detected, and the real role of serial. Each answer gives the matching check.