What is State?
Terraform records what it created in a state file that maps your config to real-world objects.
Terraform keeps a state file (terraform.tfstate) that records which real-world objects correspond to the resources in your configuration. It is how Terraform knows that aws_instance.web is really the EC2 instance with ID i-0abc123.
Why state exists
- Maps configuration to real resource IDs.
- Tracks metadata and dependencies.
- Lets
plancompute the difference between desired and current state.
Example
# Inspect what Terraform is tracking
terraform state list
# aws_instance.web
# aws_s3_bucket.data
# Show the recorded attributes of one resource
terraform state show aws_instance.webWhen to use it
- Terraform's state file records the ID of every created resource, so on the next apply it knows which real objects map to which configuration blocks.
- A team inspects terraform.tfstate after an apply to audit exactly which resource IDs and attributes Terraform is tracking before making changes.
- An engineer notices that deleting a resource block and running apply removes the actual cloud resource because Terraform diffs config against state to find orphans.
More examples
View current state list
Shows all resources currently tracked in the state file, providing an inventory of what Terraform is managing.
# List all resources tracked in state
terraform state list
# aws_instance.web
# aws_s3_bucket.data
# aws_security_group.appInspect a single resource in state
Displays all state-tracked attributes for a specific resource, useful for debugging or understanding current real-world values.
# Show all attributes Terraform is tracking for one resource
terraform state show aws_instance.web
# # aws_instance.web:
# resource "aws_instance" "web" {
# id = "i-0abc1234567890"
# ami = "ami-0c55b159cbfafe1f0"
# public_ip = "54.12.34.56"
# }State file structure (excerpt)
Shows the shape of the terraform.tfstate JSON so engineers understand what Terraform stores and why it should not be hand-edited.
{
"version": 4,
"terraform_version": "1.9.0",
"resources": [
{
"type": "aws_s3_bucket",
"name": "data",
"instances": [
{
"attributes": {
"id": "my-app-data-2024",
"bucket": "my-app-data-2024",
"region": "us-east-1"
}
}
]
}
]
}
Discussion