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,
serialandlineageincluded - Check that
sensitivemasks the display but leaves the secret in plain text - Explain why drift only shows up after a refresh
- Use the
terraform statecommands and thestate pushsafeguards - Adopt an existing resource with an
importblock and keep the state out of Git
What the state is for: three roles, not one
The official documentation gives the state three roles:
- Mapping: associate each address (
random_password.db) with the real object. - 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".
- Performance: the state works as an attribute cache. On a large
infrastructure,
-refresh=falseand-targetspeed 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:
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.
serialis a counter of state writes, not ofapplyruns. Terraform rewrites the state several times per operation: on this two-resource configuration, the firstapplyleavesserial: 3, as above, and a followingapplythat changes one resource leavesserial: 6.lineageis the UUID of the state's lineage. It acts as a safeguard forterraform 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.
With the main.tf above, terraform state show does mask the value:
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:
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:
| Command | Exit code | What it proves |
|---|---|---|
terraform plan -detailed-exitcode | 2 | the drift is seen (refresh) |
terraform plan -refresh=false -detailed-exitcode | 0 | the 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:
| Command | Role |
|---|---|
state list, state show | list, inspect (show masks secrets) |
state pull, state push | export, import the full state |
state mv | rename a resource without destroying it |
state rm | remove 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.
serialcounts writes, notapplyruns; the backup only appears at the first rewrite.- A secret marked
sensitivestays in plain text in the state;state showmasks it, but the file andshow -jsonreveal it. Onlyephemeraland write-only arguments exclude it. - Drift is only detected with a refresh (
plan= 2,-refresh=false= 0). - The safeguards live on
state push: a lowerserialand a differentlineageare 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.
Short answer
No.sensitive masks the display; the value stays in plain text in the state.Details
The documentation is clear: "Terraform stores values with thesensitive argument in both state and plan files". The terraform.tfstate file and terraform show -json contain the secret in plain text. Only ephemeral and write-only arguments keep it out of the state. Encrypt the state at rest and protect the backend.Short answer
state show is a human view that masks; the state file, read by state pull, contains the value in plain text, as does terraform show -json.Details
terraform state show random_password.db # result = (sensitive value)
terraform state pull | jq '.resources[] | select(.type=="random_password") | .instances[0].attributes.result'
The second command prints for example "zfELiMDCg4xvh0Hz", a demo value. The same attribute appears in the instance's sensitive_attributes: the mark exists, but it hides nothing of the state's content. Do not run this command in front of a shared screen or in a CI.Short answer
No. Concurrency is handled by a lock (Error acquiring the state lock), not by the serial.Details
Theserial safeguard lives 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). Locking, for its part, is automatic on any write, including with the local backend.Short answer
Because aplan without refresh relies on the state alone: drift only shows up with a refresh.Details
| Command | Code |
|---|---|
plan -detailed-exitcode |
2 (drift seen) |
plan -refresh=false -detailed-exitcode |
0 (nothing seen) |
-refresh=false to go faster can therefore miss drift.Short answer
No. "Do not directly edit this file": a manual edit breaks theserial or the dependencies.Details
Use theterraform state commands: list, show, pull, push, mv, rm. For example, state mv renames a resource without destruction (empty plan), whereas a rename in the code plans 1 resource to create and 1 to destroy.Short answer
With animport block (Terraform 1.5+), applied by terraform apply.Details
import {
to = random_password.db
id = "the-password-value-in-use"
}
The identifier depends on the provider: for random_password, it is the password value. The block is versioned and reviewed with the rest of the code, unlike the terraform import command. terraform plan -generate-config-out=file.tf can generate the configuration. If the state is lost, the first thing to try is restoring a backup.Short answer
terraform.tfstate: never. .terraform.lock.hcl: always.Details
*.tfstate
*.tfstate.*
.terraform/
The state holds the real state and secrets in plain text: it is not committed. The lock file .terraform.lock.hcl, on the contrary, is versioned: it pins the provider versions for the whole team.