In the previous lesson you understood what state is for: it is the map of identities between your code and EcoMarket's real objects, plus the dependencies and a cache of attributes. Now it is time to open it. You are going to read a terraform.tfstate field by field, understand what serial means and why lineage saves you from mixing two different states, and then learn the set of terraform state commands: the ones that only read, the ones that modify the state without touching the infrastructure and the ones you should hardly ever use. It is the module's most surgical lesson: here are the operations that fix a crooked state, and also the ones that wreck it if used carelessly.
- The format: JSON with an internal contract
The state file is JSON, but it is not a public API. HashiCorp may change its structure between versions, and indeed has done: the current format version is 4, introduced in Terraform 0.12. That distinction has a very concrete practical consequence:
| For... | Use | Do not use |
|---|---|---|
| Scripts, audits, reports | terraform show -json |
jq over terraform.tfstate |
| Exploring and understanding (as now) | jq over the file, no problem |
— |
| Modifying something | terraform state <subcommand> |
A text editor |
terraform show -json produces a documented and stable format designed to be consumed; the .tfstate is the internal storage format. In this lesson we will read the second one because we want to understand the machine from the inside, but in production always automate against the first.
- The root fields
{
"version": 4,
"terraform_version": "1.9.8",
"serial": 7,
"lineage": "8a1f0b4c-2d7e-4c11-9f3a-5b6c7d8e9f00",
"outputs": { },
"resources": [ ],
"check_results": null
}| Field | Meaning | Why it matters |
|---|---|---|
version |
Version of the file format (today, 4) |
If an old CLI sees a future format, it refuses to operate |
terraform_version |
Version of the binary that last wrote the state | Terraform will not let you apply with a binary older than the one that wrote the state |
serial |
Counter that increments on every write | It is the basis for detecting conflicting writes |
lineage |
UUID generated when the state is first created | Identifies the lineage: stops two unrelated states being mixed |
outputs |
Output values from the last apply | Served by terraform output and read by terraform_remote_state |
resources |
Array with every managed resource and data source | The heart of the file |
check_results |
Result of the check blocks (Terraform 1.5+) |
Covered in 06-05 |
Three details with real consequences:
terraform_version is a one-way lock. If somebody on the team applies with Terraform 1.10 and you have 1.9.8, your apply will fail:
Error: Invalid legacy provider address / state snapshot was created by Terraform v1.10.3, which is newer than current v1.9.8; upgrade to Terraform v1.10.3 or greater to work with this state
This is exactly what the .terraform-version = 1.9.8 file that EcoMarket keeps in the repository, managed by tfenv, prevents: the whole team and the pipeline use the same binary, so nobody "advances" the state.
serial is the lost-write detector. When Terraform uploads a state to a remote backend, it checks that the server's serial is the one it read. If somebody else wrote in the meantime, the number does not match and Terraform rejects the operation rather than trampling on someone else's work.
lineage prevents the most expensive accident. If you copy the staging state over the prod one, Terraform detects that the lineage does not match and warns you:
Error: Invalid state file: the given state file has lineage "8a1f0b4c-..." but the current state has lineage "c4e7d2a9-...".
It is not total protection — terraform state push -force bypasses it — but it is the last handrail before the drop.
- The
outputs block
outputs block"outputs": {
"name_prefix": {
"value": "ecomarket-dev",
"type": "string"
},
"endpoints": {
"value": {
"environment": "dev",
"region": "eu-west-1",
"web": "https://ecomarket-dev.ecomarket.example.com"
},
"type": ["object", {
"environment": "string",
"region": "string",
"web": "string"
}]
},
"db_connection_string": {
"value": "postgresql://ecomarket_app:an-example-password@ecomarket-dev-db:5432/ecomarket",
"type": "string",
"sensitive": true
}
}How to read it:
- Each output stores its evaluated value and its type, in Terraform's type notation:
"string"for primitives, and an array["object", {...}]or["map","string"]for composite ones. - The composite
endpointsoutput you designed in module 2 appears here as a complete object. This is what makes it possible for another configuration to readendpoints.webthroughterraform_remote_state, which you will see in Remote State. "sensitive": truemarks that the CLI must hide it when printing. The value is still in plain text, as you verified in module 2 and reviewed in the previous lesson. If something is going to be read from another configuration, think twice before publishing it as an output.
- The
resources array and each resource's identity
resources array and each resource's identityThe file's complete hierarchy, from the outside in, is this:
flowchart TB
A["terraform.tfstate<br/>version, terraform_version,<br/>serial, lineage"] --> B["outputs<br/>value + type + sensitive"]
A --> C["resources[ ]"]
C --> D["one configuration block<br/>mode, type, name, provider, module"]
D --> E["instances[ ]<br/>one per count/for_each"]
E --> F["index_key, schema_version,<br/>attributes, dependencies,<br/>sensitive_attributes"]
style A fill:#fff6e5,stroke:#b7791f
style F fill:#e8f4ff,stroke:#2b6cb0
Each element of resources describes one configuration block, not one instance:
{
"mode": "managed",
"type": "local_file",
"name": "environment",
"provider": "provider[\"registry.terraform.io/hashicorp/local\"]",
"instances": [ ]
}| Field | Values | Explanation |
|---|---|---|
mode |
managed / data |
managed is a resource; data is a data source (stored as a cache of the last read) |
type |
local_file, aws_s3_bucket... |
The resource type, which determines the provider |
name |
environment, inventory... |
The label you chose |
provider |
provider["registry.terraform.io/hashicorp/local"] |
The provider's full address; with an alias, .replica appears at the end |
module |
module.network |
Only present if the resource lives inside a module |
instances |
Array | One entry if there is no count/for_each; N entries if there is |
each |
"list" / "map" |
Present when there is a for_each; indicates the type of the keys |
The combination of module + mode + type + name + the instance index is what forms the address you use in terraform state show, in -target, in -replace and in moved blocks:
module.network.aws_subnet.private["eu-west-1a"] └─────┬──────┘└───┬─────┘└──┬───┘└─────┬──────┘ module type name index_key
- Inside
instances: attributes, dependencies and indexes
instances: attributes, dependencies and indexes"instances": [
{
"index_key": "dev",
"schema_version": 0,
"attributes": {
"content": "{\"environment\":\"dev\",\"instances\":1}",
"content_base64": null,
"directory_permission": "0777",
"file_permission": "0644",
"filename": "./ecomarket-dev-environment.json",
"id": "5f2c8a1d9b0e3c7f4a6d2e8b1c5f9a3d7e0b4c26"
},
"sensitive_attributes": [],
"dependencies": [
"random_pet.suffix"
]
}
]| Field | Meaning |
|---|---|
index_key |
The instance's key. A number if it comes from count (0, 1), a string if it comes from for_each ("dev"). Absent if the resource is not repeated |
schema_version |
Version of the provider schema the attributes were written with. If the provider moves up a version and changes the schema, it runs an automatic state migration and updates this number |
attributes |
The complete snapshot of the object after the last apply, including the arguments you did not write and that the provider filled in with its default values |
sensitive_attributes |
Attribute paths the CLI must hide when printing. It neither encrypts nor omits anything |
dependencies |
Addresses this instance depends on. This is what allows destroy to be ordered with no configuration |
private |
Base64 string with the provider's internal data (for instance, the timeouts). Not to be touched |
status |
Appears as "tainted" if the object was marked for replacement after a failed apply |
Two important observations:
attributes contains more than you wrote. In the example you can see content_base64 and directory_permission, which are not in your .tf. They are default values from the provider's schema. That is why the state is usually far bigger than you expect: a single aws_instance can take up 200 lines.
index_key explains the count problem. When in module 2 you saw that removing an element from the middle of a list triggered cascading replacements, the reason is this field: the state indexes by 0, 1, 2, and a shift in the list changes which real object corresponds to each number. With for_each, the index_key is "web" or "dev", which does not shift. Migrating from one to the other without destroying anything is the subject of Declarative Refactoring.
- A complete EcoMarket
terraform.tfstate, annotated
terraform.tfstate, annotatedThis is the real state of EcoMarket's infra/ directory after applying the module 2 configuration in dev, trimmed to the essentials. The // comments do not exist in the real file (JSON does not allow them): they are here so you can read it.
{
// Format 4: Terraform 0.12 onwards.
"version": 4,
// The binary that wrote it. Matches the repo's .terraform-version.
"terraform_version": "1.9.8",
// Seventh write of this state.
"serial": 7,
// Lineage: born with the first apply and never changes.
"lineage": "8a1f0b4c-2d7e-4c11-9f3a-5b6c7d8e9f00",
"outputs": {
"name_prefix": { "value": "ecomarket-dev", "type": "string" },
"endpoints": {
"value": {
"environment": "dev",
"region": "eu-west-1",
"web": "https://ecomarket-dev.ecomarket.example.com"
},
"type": ["object", {"environment":"string","region":"string","web":"string"}]
}
},
"resources": [
{
// A data source: the state stores the LAST READ, as a cache.
"mode": "data",
"type": "local_file",
"name": "base_tags",
"provider": "provider[\"registry.terraform.io/hashicorp/local\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"content": "{\"ManagedBy\":\"terraform\",\"Owner\":\"plataforma\"}",
"filename": "./templates/base-tags.json",
"id": "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"
}
}
]
},
{
"mode": "managed",
"type": "random_pet",
"name": "suffix",
"provider": "provider[\"registry.terraform.io/hashicorp/random\"]",
"instances": [
{
"schema_version": 0,
"attributes": {
"id": "cheerful-mammoth",
"keepers": { "environment": "dev" },
"length": 2,
"prefix": null,
"separator": "-"
},
"sensitive_attributes": []
// No "dependencies": it references nobody.
}
]
},
{
"mode": "managed",
"type": "local_file",
"name": "environment",
"provider": "provider[\"registry.terraform.io/hashicorp/local\"]",
// "each": "map" indicates that this resource uses for_each over a map.
"each": "map",
"instances": [
{
// for_each => the key is a STRING.
"index_key": "dev",
"schema_version": 0,
"attributes": {
"content": "{\"environment\":\"dev\",\"instances\":1}",
"filename": "./ecomarket-dev-environment.json",
"file_permission": "0644",
"id": "5f2c8a1d9b0e3c7f4a6d2e8b1c5f9a3d7e0b4c26"
},
"sensitive_attributes": [],
// Recorded dependencies: they allow destruction in reverse order
// even when the configuration no longer exists.
"dependencies": ["random_pet.suffix"]
},
{
"index_key": "prod",
"schema_version": 0,
"attributes": {
"content": "{\"environment\":\"prod\",\"instances\":4}",
"filename": "./ecomarket-prod-environment.json",
"file_permission": "0644",
"id": "7a3e1c5d8f2b0a9e4c6d1f3b8e5a2c7d0b4f9e13"
},
"sensitive_attributes": [],
"dependencies": ["random_pet.suffix"]
}
]
}
],
"check_results": null
}With this file in front of you, go over the correspondences:
terraform state listwould returndata.local_file.base_tags,local_file.environment["dev"],local_file.environment["prod"]andrandom_pet.suffix. Addresses are built exactly frommode+type+name+index_key.- The
data sourceis there as a cache; it is read again on the nextplan, so its content is not authoritative. - The two instances of
local_file.environmentshare a block inresourcesand are told apart byindex_key.
terraform.tfstate.backup: when it is written and what it is for
terraform.tfstate.backup: when it is written and what it is forNext to the state there is, almost always, a second file:
$ ls -la
-rw------- 1 dev dev 4821 22 Sep 12:04 terraform.tfstate
-rw------- 1 dev dev 4102 22 Sep 12:04 terraform.tfstate.backupWhat it is: the copy of the state immediately before the last write. Terraform generates it automatically with the local backend just before overwriting terraform.tfstate.
When it is written:
| Operation | Does it generate a backup? |
|---|---|
terraform apply with changes |
Yes |
terraform apply -refresh-only |
Yes |
terraform destroy |
Yes |
terraform state mv / rm / push |
Yes |
terraform plan |
No (it does not write state) |
| Remote backends | Not this way: versioning comes from the backend |
What it is not: a backup strategy. It keeps a single generation. If you run two bad operations in a row, the backup already contains the first one and the good state is gone. That is why remote backends with object versioning are the real backup.
How to use it in an emergency (the full recovery procedure belongs to State Management Issues):
# 1. Before anything else, copy BOTH files somewhere safe.
$ cp terraform.tfstate /tmp/broken-state-$(date +%s).json
$ cp terraform.tfstate.backup /tmp/previous-state-$(date +%s).json
# 2. Check that the backup is the one you think it is (look at the serial).
$ jq '{serial, lineage, resources: (.resources | length)}' terraform.tfstate.backup
{ "serial": 6, "lineage": "8a1f0b4c-...", "resources": 3 }
# 3. Only then, restore.
$ cp terraform.tfstate.backup terraform.tfstate
$ terraform plan # check that the plan comes out cleanEcoMarket's .gitignore already ignores terraform.tfstate.backup for the same reason as the state: it contains the same thing, secrets included.
- Contrast with
.terraform.lock.hcl
.terraform.lock.hclIt is common to confuse the two files because both sound like "things Terraform keeps". They are nothing alike:
terraform.tfstate |
.terraform.lock.hcl |
|
|---|---|---|
| What it stores | The managed real objects | The providers' versions and hashes |
| Who writes it | apply, destroy, state * |
init |
| Into Git? | Never | Always |
| Does it contain secrets? | Yes, in plain text | No |
| If you delete it | Terraform forgets the infrastructure | It is regenerated with terraform init |
| Scope | Per configuration and environment | Per configuration |
You already studied the lock file thoroughly in Providers; here only the contrast matters. And there is a third confusion worth clearing up once and for all:
./terraform.tfstate→ the real state. Do not delete../.terraform/terraform.tfstate→ the backend configuration when you use remote state, not the state. Regenerated byinit../.terraform.tfstate.lock.info→ the temporary lock file, which only exists during an operation. It is the subject of State Locking.
- The
terraform state commands, one by one
terraform state commands, one by oneThe whole terraform state subset operates on the state, not on the infrastructure. None of these commands creates or destroys anything real. That makes them safe for the infrastructure and unsafe for the state: a misplaced state rm leaves orphaned resources that nobody manages and that will carry on billing.
| Subcommand | Reads or writes | Risk | Declarative alternative |
|---|---|---|---|
list |
Reads | None | — |
show |
Reads | None | — |
pull |
Reads | None | — |
mv |
Writes | Medium | moved block |
rm |
Writes | High | removed block |
replace-provider |
Writes | Medium | — |
push |
Writes | Very high | — |
The two declarative alternatives in the last column are the content of Declarative Refactoring, and they are the recommended way of doing these operations today. Even so, you need to know the commands: there are rescue situations where there is no other option.
9.1. terraform state list
An inventory of addresses. It accepts a filter by address, module prefix included:
# Everything.
$ terraform state list
data.local_file.base_tags
local_file.environment["dev"]
local_file.environment["prod"]
random_pet.suffix
# Just one resource, with all its instances.
$ terraform state list local_file.environment
local_file.environment["dev"]
local_file.environment["prod"]
# A specific instance (mind the quote escaping in the shell).
$ terraform state list 'local_file.environment["dev"]'
local_file.environment["dev"]
# Everything inside a module.
$ terraform state list module.network
module.network.aws_vpc.main
module.network.aws_subnet.private["eu-west-1a"]
# Search by the object's real ID rather than by address.
$ terraform state list -id=cheerful-mammoth
random_pet.suffixShell tip: addresses with square brackets and quotes have to be protected with single quotes, because
[is a glob character for Bash.terraform state list local_file.environment["dev"]may not work;'local_file.environment["dev"]'does.
9.2. terraform state show
The attributes of one instance, formatted as HCL:
$ terraform state show 'local_file.environment["dev"]'
# local_file.environment["dev"]:
resource "local_file" "environment" {
content = jsonencode({ environment = "dev", instances = 1 })
directory_permission = "0777"
file_permission = "0644"
filename = "./ecomarket-dev-environment.json"
id = "5f2c8a1d9b0e3c7f4a6d2e8b1c5f9a3d7e0b4c26"
}It is useful for two very practical things: seeing the real id Terraform has recorded, and discovering attributes you did not know existed before writing them into the code.
9.3. terraform state mv: renaming and moving
It changes a resource's address inside the state, without touching anything real. The three use cases:
# Case 1: rename a resource.
# The code goes from local_file.inventory to local_file.general_inventory.
$ terraform state mv local_file.inventory local_file.general_inventory
Move "local_file.inventory" to "local_file.general_inventory"
Successfully moved 1 object(s).# Case 2: move a resource into a module.
# What you will do in module 4 when extracting the network into module.network.
$ terraform state mv aws_vpc.main module.network.aws_vpc.main
Move "aws_vpc.main" to "module.network.aws_vpc.main"
Successfully moved 1 object(s).
# And the reverse: take it out of the module.
$ terraform state mv module.network.aws_vpc.main aws_vpc.main# Case 3: from a count index to a for_each key.
# The problem module 2 left open: one command PER INSTANCE.
$ terraform state mv 'local_file.service[0]' 'local_file.service["web"]'
$ terraform state mv 'local_file.service[1]' 'local_file.service["api"]'
$ terraform state mv 'local_file.service[2]' 'local_file.service["batch"]'
$ terraform state mv 'local_file.service[3]' 'local_file.service["cron"]'
Successfully moved 1 object(s).# Case 4: move a resource BETWEEN different states.
$ terraform state mv -state-out=../other-config/terraform.tfstate \
local_file.inventory local_file.inventoryBefore any state mv, rehearse it with -dry-run:
$ terraform state mv -dry-run 'local_file.service[0]' 'local_file.service["web"]'
Would move "local_file.service[0]" to "local_file.service[\"web\"]"The problem with state mv, and the reason an alternative exists: it is imperative. It is run by hand, in a terminal, by one person. It does not show up in the PR, it is not recorded in Git, and whoever deploys after you from another machine or from CI will never run it — so their apply will destroy and recreate. The moved block solves exactly that, and it is what you will see in Declarative Refactoring.
9.4. terraform state rm: stop managing without destroying
It removes a resource from the state. The real object still exists; Terraform simply forgets about it:
$ terraform state rm 'local_file.environment["staging"]'
Removed local_file.environment["staging"]
Successfully removed 1 resource instance(s).Legitimate cases:
- A resource is handed over to another team or another configuration (removed from here and imported there).
- You are splitting a monolithic configuration into several and moving pieces around.
- A resource was left in the state but no longer exists in reality and the refresh does not detect it (a rescue situation).
What you always have to do afterwards: remove the block from the .tf as well. If you do not, the next plan will see a resource in the configuration that is not in the state and will propose creating it again, leaving two real objects where there should be one.
# After the rm, with the block still in the .tf:
$ terraform plan
# local_file.environment["staging"] will be created
Plan: 1 to add, 0 to change, 0 to destroy. # <-- the duplicate on its wayJust as with mv, there is a declarative alternative — the removed block — that leaves a trace in the code and in the PR.
9.5. terraform state pull and terraform state push
# pull: downloads the state from the backend and prints it to standard output.
# It works the same with a local or a remote backend. It is read-only and safe.
$ terraform state pull > state-$(date +%Y%m%d-%H%M%S).json
$ terraform state pull | jq '{serial, lineage, resources: (.resources | length)}'
{
"serial": 7,
"lineage": "8a1f0b4c-2d7e-4c11-9f3a-5b6c7d8e9f00",
"resources": 3
}state pull is the correct way of taking a point-in-time copy before a delicate operation, and it works with any backend.
# push: UPLOADS a state file to the backend. It is the last resort.
$ terraform state push corrected-state.jsonWhy push is the last resort:
- It replaces the entire state, not a part of it. One editing mistake takes everything with it.
- Terraform checks
lineageandserial, but-forceskips both checks, and whoever usespushusually ends up using-force. - It almost always implies that you have edited the JSON by hand, which is the single most error-prone operation in the whole of Terraform.
- If the backend has versioning, restoring an earlier version of the object is safer and more traceable than pushing an edited file.
Before a push, consider whether the problem cannot be solved with state mv, state rm or import. Almost always it can.
9.6. terraform state replace-provider
It changes the provider recorded for a set of resources. It is used when a provider changes namespace — for example, when migrating from a community provider to an official one, or after the OpenTofu fork:
$ terraform state replace-provider \
'registry.terraform.io/-/local' \
'registry.terraform.io/hashicorp/local'
Terraform will perform the following actions:
~ Updating provider:
- registry.terraform.io/-/local
+ registry.terraform.io/hashicorp/local
Changing 3 resources:
local_file.environment["dev"]
local_file.environment["prod"]
data.local_file.base_tags
Do you want to make these changes? Only 'yes' will be accepted to continue.
Enter a value: yesIt is a purely metadata operation: it does not touch a single attribute. Afterwards, you have to update required_providers in the code and run terraform init.
- Deprecated commands:
taint, untaint and refresh
taint, untaint and refresh10.1. taint / untaint versus apply -replace=
Marking a resource as "tainted" made the next apply destroy and recreate it. It is useful when an object exists but is wrong: an instance that booted with faulty user_data, a corrupted file.
# The OLD way, deprecated since Terraform 0.15.2:
$ terraform taint 'local_file.environment["dev"]'
$ terraform apply # ...and only now do you find out what will happen
# The MODERN way:
$ terraform plan -replace='local_file.environment["dev"]' # first you SEE it
$ terraform apply -replace='local_file.environment["dev"]' # and then you do itterraform taint |
terraform apply -replace= |
|
|---|---|---|
| Modifies the state immediately | Yes | No |
| Lets you see the plan first | No | Yes |
| Undoing | terraform untaint |
Not needed: you do not apply |
| Current status | Deprecated | Recommended |
The flaw in taint is the same as in refresh: it changes the state before you see anything. If you get the address wrong, you have to remember to run untaint. With -replace=, if you get it wrong you simply do not type yes.
untaint is still useful in one case: when an apply fails halfway through and Terraform marks the object as tainted on its own, but you verify that it is actually fine.
10.2. terraform refresh versus -refresh-only
# Deprecated since 0.15.4: it updates the state WITHOUT showing you what changes.
$ terraform refresh
# Modern: it shows you the drift and asks for confirmation.
$ terraform apply -refresh-onlyYou already saw this in the previous lesson. The logic is identical to that of taint: HashiCorp has been retiring the commands that write the state blind and replacing them with options in the plan/apply flow, where there is always a review in between. It is a good general criterion: if a command modifies the state without showing you a plan, be suspicious.
- Backing up and versioning the state
With the state held locally, the backup strategy depends entirely on you. With the state held remotely, the backend provides it. The minimum acceptable at EcoMarket:
| Level | Measure | Where |
|---|---|---|
| 1 | terraform.tfstate.backup (one generation) |
Automatic, local backend |
| 2 | Manual copy before a delicate operation | terraform state pull > copy.json |
| 3 | Object versioning in the bucket | S3/GCS/Blob backend → 03-03 |
| 4 | Cross-region replication and a retention policy | Bucket configuration |
| 5 | A documented restore rehearsal | The team's runbook |
Level 3 is the one that really changes things: with versioning enabled, every write of the state — bad ones included — generates a new version and the previous ones are still there. Recovering means restoring a version of the object, not rebuilding anything.
# With versioning on S3: list the versions of the state object (example).
$ aws s3api list-object-versions \
--bucket ecomarket-tfstate \
--prefix ecomarket/dev/terraform.tfstate \
--query 'Versions[:3].[VersionId,LastModified,Size]' --output tableAnd one daily hygiene rule: before touching the state with mv, rm, push or replace-provider, do a terraform state pull into a dated file. It costs two seconds and is the difference between a fright and an incident.
- What never to do with the state
| Action | What it looks like | What really happens | Severity |
|---|---|---|---|
| Editing the JSON by hand | "I am only changing one attribute" | A serial that was not incremented, invalid JSON, or broken dependencies that break the destroy |
Very high |
| Versioning it in Git | "That way the whole team has it" | Plain-text secrets leaked into the entire history, plus unresolvable merge conflicts | Very high |
| Copying it between environments | "I will start from dev to build prod" |
Terraform believes the prod objects are the dev ones and "corrects" production |
Critical |
| Sharing it to ask for help | "I will send you the tfstate, see what you make of it" | Production passwords and keys in a chat or a ticket | Very high |
| Deleting it to "start clean" | "It will just recreate it" | Terraform forgets everything and creates duplicates; the old objects are orphaned and still billing | Critical |
state rm without removing the .tf block |
"I do not manage it any more" | The next plan creates it again: two real objects |
High |
state push -force |
"I will just ignore the warning" | It skips the lineage and serial checks; it tramples on other people's work |
Critical |
Running two apply operations at once |
"We are in a hurry" | Lost writes and an inconsistent state. Locking prevents it: 03-04 | Critical |
Security note. If a state with secrets has reached Git, a chat channel or a ticketing system, the problem is not fixed by deleting the message: you have to rotate every secret it contained and inform the security team. An exposed secret is a burnt secret, even if the file is no longer visible.
Common Mistakes and Tips
- Automating with
jqoverterraform.tfstate. The format is internal and may change. Useterraform show -json, which is stable and documented. - Forgetting the single quotes on addresses with square brackets. Bash interprets
[as a glob character and the command fails with a cryptic error. - Running
state rmthinking it destroys the resource. It does not destroy it: it abandons it. To destroy, useterraform destroyorapplyafter removing the block. - Running
state mvfrom your laptop and telling nobody. When CI runs theapply, it will not have that move and will destroy what you "rescued". Usemovedblocks. - Confusing
.terraform/terraform.tfstatewith./terraform.tfstate. The first is the backend configuration and is regenerated; the second is Terraform's memory. - Believing that
terraform.tfstate.backupis a sufficient backup. It is a single generation and is overwritten by the next operation. - Tip: always run
terraform state mv -dry-runbefore the real move. Seeing the expected output costs a second. - Tip: after any state operation, validate with
terraform plan. A plan of0 to add, 0 to change, 0 to destroyis the confirmation that the state is still consistent with reality. - Tip: if a
state showreturns attributes you do not recognise, do not delete them from the code: they are provider defaults and it is normal for them to be there.
Exercises
Start from a fresh directory with the local and random providers, applying EcoMarket's module 2 configuration.
Exercise 1: reading the state like a forensic analyst
- Create
local_file.environmentwithfor_each = toset(["dev","staging","prod"])and arandom_pet.suffix, and apply. - Without opening the file, answer with commands: how many resources are there? What is the
serial? Whatiddoes the"prod"instance have? - Open
terraform.tfstateand locate: thelineage, theeachfield, the threeindex_keyvalues and thedependenciesof one instance. - Change the content of one of the instances in the code, apply, and check how the
serialchanges. How much has it gone up, and why? - Explain what
terraform.tfstate.backupnow contains.
Exercise 2: renaming without destroying, with state mv
- With the previous configuration applied, rename
local_file.environmenttolocal_file.environment_configin the code. - Run
terraform planwithout applying and note down the summary. - Use
terraform state mv -dry-runto preview the three moves needed, then run them for real. - Run
terraform planagain. What does it say now? - Answer: if your colleague checks out the branch with the rename but without your
state mvcommands, what will herplanshow? What conclusion do you draw about the method?
Exercise 3: state rm and the duplicate trap
- Run
terraform state rm 'local_file.environment_config["staging"]'and check that the real file still exists on disk. - Run
terraform planwithout touching the code. What does it propose and why is it a problem? - Remove
"staging"from thefor_eachand plan again. What does it say now? - Bring the resource back into the state. Which command would you use? (You do not need to run it: reason out the answer and say which lesson covers it.)
- Take a copy of the state with
terraform state pulland check withjqthat theserialand the number of resources are what you expect.
Solutions
Solution 1:
$ terraform state list | wc -l
4
$ terraform state pull | jq '.serial'
3
$ terraform state show 'local_file.environment["prod"]' | grep '^ id'
id = "7a3e1c5d8f2b0a9e4c6d1f3b8e5a2c7d0b4f9e13"In the file you will find "lineage" at the root, "each": "map" in the local_file.environment block (because toset() produces string keys; the state records it as a map of instances), one "index_key" per environment and, if the resource references the suffix, "dependencies": ["random_pet.suffix"].
Point 4: the serial goes up one at a time for each write of the state, not for each changed resource. An apply that modifies three files raises the serial by 1 if it writes once at the end, although in practice Terraform writes after each resource and you will see bigger increments. What matters is that it always grows and that you never edit it yourself.
Point 5: terraform.tfstate.backup contains the state as it was before that last apply, that is, with the old content of the modified file and the previous serial.
Solution 2:
# Point 2: the state knows nothing about the rename.
$ terraform plan
Plan: 3 to add, 0 to change, 3 to destroy.# Point 3:
$ terraform state mv -dry-run 'local_file.environment["dev"]' 'local_file.environment_config["dev"]'
Would move "local_file.environment[\"dev\"]" to "local_file.environment_config[\"dev\"]"
$ terraform state mv 'local_file.environment["dev"]' 'local_file.environment_config["dev"]'
$ terraform state mv 'local_file.environment["staging"]' 'local_file.environment_config["staging"]'
$ terraform state mv 'local_file.environment["prod"]' 'local_file.environment_config["prod"]'
Successfully moved 1 object(s).Point 5: your colleague will get exactly the plan from point 2 — 3 to add, 0 to change, 3 to destroy — because the remote state she uses does not have your moves... unless the state is shared, in which case the moves are already done and she will see a clean plan. With a local state, every person would have to run the same three commands by hand, in the same order, without making a mistake.
The conclusion is twofold: the state has to be shared (the whole of module 3) and refactoring has to travel in the code, not in the memory of whoever did it. That last point is the moved block of 03-05.
Solution 3:
$ terraform state rm 'local_file.environment_config["staging"]'
Removed local_file.environment_config["staging"]
$ ls ecomarket-staging-environment.json
ecomarket-staging-environment.json # still there: rm does NOT destroy# Point 2:
$ terraform plan
# local_file.environment_config["staging"] will be created
Plan: 1 to add, 0 to change, 0 to destroy.It is a problem because the object already exists. With a local_file the result is that it gets overwritten, which is harmless; with a bucket or a database, the apply would fail with a duplicate name or, worse, would create a second real object that nobody manages and that keeps costing money.
# Point 3: once "staging" is removed from the for_each, configuration and state match.
$ terraform plan
No changes. Your infrastructure matches the configuration.Point 4: to bring it back into the state you use terraform import (or the declarative import block), which associates a configuration address with an existing object's id. It is covered in Importing Resources. state push is not the answer: that would mean editing the JSON by hand, precisely what has to be avoided.
# Point 5:
$ terraform state pull > copy-$(date +%Y%m%d-%H%M%S).json
$ jq '{serial, resources: (.resources | length)}' copy-*.json
{ "serial": 6, "resources": 2 }Conclusion
There is nothing opaque left in the state file:
- It is a JSON in an internal format (version 4). To read it and learn,
jq; to automate,terraform show -json, which is the stable format. - At the root live
version,terraform_version(which stops you applying with an older binary),serial(which detects conflicting writes),lineage(which stops unrelated states being mixed) and the evaluatedoutputs. - Each entry in
resourcesis a configuration block — withmode,type,name,providerand, where appropriate,module— and contains one or severalinstancesidentified byindex_key: a number withcount, a string withfor_each. - Each instance stores
schema_version, all theattributes(including the ones filled in by the provider),dependenciesso it can destroy in reverse order, andsensitive_attributes, which hides when printing but encrypts nothing. terraform.tfstate.backupis a single previous generation: useful in a pinch, insufficient as a backup. The real backup is the remote backend's versioning.- The
terraform statecommands operate on the state and never on the infrastructure:listandshowto read,pullto copy,mvto rename or move (including into and out of modules, and from acountindex to afor_eachkey),rmto stop managing without destroying,replace-providerto change namespace, andpushas a last resort. taint/untaintandrefreshare deprecated for the same reason: they write the state without showing you a plan. Their replacements areapply -replace=andapply -refresh-only.- And there is a short list of things that are never done: editing the JSON, versioning it, copying it between environments, sharing it or deleting it to "start clean".
There remains, however, the underlying problem that has run through the whole lesson: you have done a state mv from your terminal and nobody else knows; your colleague has her own terraform.tfstate on her laptop; the pipeline has none at all. As long as the state remains a local file, EcoMarket is not a team, it is three people with three different imaginary infrastructures. In Remote State you take the leap: you move the state to a shared, encrypted and versioned backend, and you learn to connect configurations to each other with terraform_remote_state.
