What is Terraform State?
Terraform state is a record of the infrastructure that Terraform has created and is managing. It serves as the source of truth for what exists, enabling Terraform to determine what changes need to be made to match your configuration.State is the bridge between your declarative configuration and the real infrastructure in your cloud provider. Without state, Terraform wouldn’t know which resources it manages or what their current configuration is.
The State Structure
State is represented by thestates.State struct:
states/state.go and states/module.go
What State Contains
Resource Instances
For each managed resource, state tracks:- Resource address - Unique identifier (e.g.,
aws_instance.web[0]) - Provider - Which provider manages this resource
- Attributes - Current attribute values
- Dependencies - Recorded dependencies
- Metadata - Creation time, schema version, etc.
Output Values
Root module outputs are persisted:Child module outputs are calculated during execution but not persisted. Only root module outputs survive between runs.
State Metadata
State files include metadata:- Terraform version - Version that last wrote the state
- Serial - Incremented on each write (prevents conflicts)
- Lineage - UUID identifying this state lineage (prevents mixing states)
- Timestamp - When state was last modified
State Managers
State is accessed through state managers that implement thestatemgr interfaces:
statemgr package
Filesystem State Manager
The defaultstatemgr.Filesystem writes state to local files:
Remote State Managers
Remote backends provide state managers that store state remotely:- S3 - Stores in AWS S3 bucket
- Azure Blob - Stores in Azure Storage
- GCS - Stores in Google Cloud Storage
- Terraform Cloud - Stores in HashiCorp’s service
- Consul - Stores in HashiCorp Consul
- Reading from remote storage
- Writing to remote storage
- Locking to prevent concurrent modifications
- Refreshing to get latest version
State Locking
State locking prevents concurrent modifications:Lock Information
Thread-Safe State Access
During graph walks, multiple vertices may access state concurrently. Terraform usesstates.SyncState to provide thread-safe access:
states/sync.go
The graph walker creates a
SyncState wrapper around the state, which all vertex executions use. This ensures concurrent read/write operations don’t corrupt the state.Source: docs/architecture.mdState Lifecycle
State evolves through the Terraform workflow:
Source:
docs/resource-instance-change-lifecycle.md
State Refresh
Refreshing updates state from the real infrastructure:Refresh Process
Source:
docs/resource-instance-change-lifecycle.md
Drift Detection
Providers must distinguish between: Normalization - Same value in different format:State Snapshots
Every state write creates a snapshot:State Versions
The state file format has evolved:- Version 1-3 - Legacy formats (Terraform < 0.12)
- Version 4 - Current format (Terraform >= 0.12)
Lineage Tracking
Lineage prevents accidentally mixing different states:State Commands
Terraform provides commands for state manipulation:List Resources
Show Resource
Move Resources
Remove Resources
Import Resources
ImportResourceState function.
Remote State
Remote state enables collaboration:Benefits of Remote State
Collaboration
Multiple team members can work with the same state
Locking
Prevents concurrent modifications and race conditions
Backup
State is stored durably in cloud storage
Encryption
Sensitive data can be encrypted at rest
State Sharing
Useterraform_remote_state data source to reference another state:
Sensitive Data in State
State files may contain sensitive data:- Database passwords
- API keys
- Private keys
- Any value marked as
sensitive
Securing State
Use Remote State with Encryption
Use Remote State with Encryption
Store state in encrypted remote storage:
Enable State Locking
Enable State Locking
Use backends that support locking to prevent corruption:
Restrict Access
Restrict Access
Use IAM policies to limit who can read/write state:
Use Terraform Cloud
Use Terraform Cloud
Terraform Cloud provides:
- Encrypted state storage
- State versioning
- Access controls
- Audit logs
State Versioning
Many remote backends support versioning:- Rollback to previous states
- Audit trail of changes
- Recovery from corruption
State Migration
Migrate state between backends:State Backup
Terraform automatically creates backups:Local Backups
When using local state:Remote Backups
When using remote state with versioning:- Each state write creates a new version
- Old versions are retained according to backend policy
Workspace State
Workspaces have separate states:docs/architecture.md
Best Practices
Always Use Remote State for Teams
Always Use Remote State for Teams
Use remote state with locking when collaborating:
Enable State Versioning
Enable State Versioning
Always enable versioning on state storage to enable recovery.
Never Manually Edit State
Never Manually Edit State
Use
terraform state commands instead of editing state files directly.Manual edits can corrupt state or break Terraform’s assumptions.Backup Before Major Changes
Backup Before Major Changes
Create a state backup before:
- Major refactoring
- Version upgrades
- Backend migrations
Monitor State Size
Monitor State Size
Large state files (>10MB) can slow Terraform operations.Consider:
- Splitting into multiple state files
- Using modules with separate state
- Removing unused resources
Troubleshooting
State Locked
- Wait for other Terraform process to complete
- If process crashed, force unlock:
State Corruption
- Restore from backup
- Upgrade Terraform version
- Run
terraform state replace-providerif needed
Drift Detected
- Review changes with
terraform plan - Accept drift with
terraform apply - Or use
ignore_changesto accept permanently
Next Steps
Core Concepts Overview
Return to the overview to explore other core concepts