Delve into Terraform’s state management mechanism — the most critical concept that distinguishes Terraform from simple provisioning tools.
What Will You Learn? #
State is a JSON file that records the mapping between your Terraform configuration and the actual resources in the infrastructure. Poor state management is the #1 cause of problems in production Terraform. This section covers all aspects of state, from local to remote, from locking to migration.
Articles in This Section #
| Article | Main Topic |
|---|---|
| Local | Local state files — how they work and their limitations |
| Remote | Remote backends (S3, GCS, Azure Blob) for team collaboration |
| Locking | Preventing concurrent operations that corrupt state |
| Import | Bringing existing resources into Terraform state |
| Migration | Moving state between backends or reorganizing |
| Anti-Pattern | Common state management mistakes to avoid |
State Flow #
flowchart TD
subgraph Write Path
TF["Terraform Apply"] --> SF["State File"]
SF -->|Lock| RB["Remote Backend<br/>(S3, GCS, Azure)"]
end
subgraph Read Path
TP["Terraform Plan"] -->|Read| SF2["Read State"]
SF2 -->|Compare| API["Cloud API<br/>(Actual State)"]
end
subgraph Drift
API -->|Diff| Drift["Drift Detected"]
Drift -->|Inform| TP
end
TF --> TP
style Write Path fill:#e3f2fd
style Read Path fill:#e8f5e9
style Drift fill:#fff3e0Local vs Remote State #
flowchart LR
subgraph Local["Local State"]
LS["terraform.tfstate<br/>On a local machine"]
LR["Only for\nsolo developers"]
end
subgraph Remote["Remote State"]
RS["Backend: S3, GCS,<br/>Azure Blob, Terraform Cloud"]
RL["Built-in locking"]
RV["Version history"]
RT["Team collaboration"]
end
Local -->|"Migrate"| Remote
style Local fill:#ffebee
style Remote fill:#e8f5e9State Anti-Patterns #
flowchart TD
AP1["❌ Manual state file edits"] --> FIX1["✅ Use terraform state mv/rm"]
AP2["❌ Shared state file without locking"] --> FIX2["✅ Remote backend + locking"]
AP3["❌ Secrets stored in state"] --> FIX3["✅ Encrypt state + limit access"]
AP4["❌ No state backup"] --> FIX4["✅ Enable backend versioning"]
style AP1 fill:#ffebee
style AP2 fill:#ffebee
style AP3 fill:#ffebee
style AP4 fill:#ffebee
style FIX1 fill:#e8f5e9
style FIX2 fill:#e8f5e9
style FIX3 fill:#e8f5e9
style FIX4 fill:#e8f5e9Good state management is the foundation of reliable Terraform in production. Continue to Security to learn how to protect state files and secrets.