- What the state file is
- What information the state stores
- Why Terraform needs state
- Basic Terraform commands that create and use state
- Think of the state file as Terraform’s memory. It records what Terraform has created and stores metadata that maps your
.tfconfiguration to real infrastructure objects. - By default, Terraform writes state as JSON to
terraform.tfstatein the working directory unless you configure a remote backend.
State file format (simplified)
State is stored in JSON. Below is a short, simplified excerpt illustrating typical fields in a small state file:
- Initialize the working directory (creates or configures the backend and initializes providers):
- Preview changes (Terraform compares local configuration, saved state, and provider data):
- Apply changes (updates infrastructure and writes the new state):
The state file is essential for accurate planning and incremental changes. If the state is missing, corrupted, or out of sync, Terraform cannot reliably determine what changes to make.
- Sensitive data: The state file can include sensitive values (resource IDs, IPs, endpoints, and sometimes secrets). Do not commit
terraform.tfstateorterraform.tfstate.backupto source control. - Team use and CI/CD: For collaborative environments, use a remote backend (for example, Terraform Cloud, S3 with DynamoDB locking, or another supported backend) to share state and enable locking. Remote backends help prevent conflicts and support secure storage.
- Encrypt and restrict access: Ensure backend storage is encrypted at rest and access is limited to only those systems and users that need it.
- We will inspect a real state file and step through how Terraform uses it during
planandapply. - Advanced materials will cover remote backends, state locking, secure handling of sensitive state contents, and state migration strategies.