Terraform 23: What Terraform state is and why it exists
easy⏱ 5 mincourseterraform
State is the map from config to reality
When you run terraform apply, Terraform creates real resources but also writes state: a JSON file linking each resource address (like azurerm_resource_group.orders) to the actual object's id and last-known attributes. On the next run it diffs desired config against recorded state to compute a minimal plan. Without state, Terraform would have no memory of what it already owns.
# Config you wrote
resource "azurerm_resource_group" "orders" {
name = "myorg-orders-dev-rg"
location = "westus2"
}
# What state records after apply (simplified terraform.tfstate)
# {
# "resources": [{
# "type": "azurerm_resource_group",
# "name": "orders",
# "instances": [{
# "attributes": {
# "id": "/subscriptions/.../resourceGroups/myorg-orders-dev-rg",
# "location": "westus2"
# }
# }]
# }]
# }
Never hand-edit state
The .tfstate file is Terraform's source of truth, not yours. Editing it by hand corrupts the config↔reality mapping and can make Terraform try to recreate or orphan resources. Change infrastructure through .tf files and terraform apply; change state only through dedicated commands (terraform state ..., import, moved) covered later in this tier.
State can hold secrets — keep it out of git
State stores every attribute of every resource, including values a provider marked sensitive (connection strings, generated passwords). Add *.tfstate and *.tfstate.backup to .gitignore. This is a core reason teams move state to a locked-down remote backend instead of leaving it on disk — the next lessons.
Model a state entry
Fill the stateEntry object so address is "azurerm_resource_group.orders", type is "azurerm_resource_group", name is "orders", and id is any non-empty cloud id string. Then log stateEntry.id.