This article covers OpenTofu’s state management, including the state file’s purpose, best practices, and how to maintain reliability and security.
In this lesson, we’ll dive into OpenTofu’s state management. You’ll learn what the state file is, why it matters, and best practices for keeping it reliable and secure.
When you execute tofu apply for the first time, OpenTofu generates a JSON state file named terraform.tfstate in your working directory, along with a backup terraform.tfstate.backup. This file records every resource managed by OpenTofu—its IDs, attributes, dependencies, and provider metadata.Example configuration:
Before creating an execution plan, OpenTofu refreshes the state by comparing it to real-world infrastructure:
Copy
Ask AI
$ tofu planaws_instance.cerberus: Refreshing state... [id=i-1db6bfe81bd1e3ed7]No changes. Your infrastructure matches the configuration.Plan: 0 to add, 0 to change, 0 to destroy.
This ensures that any drift is detected before making changes.
Skipping state refresh may speed up large operations but risks applying changes on outdated state. Only use this flag if you fully understand the consequences.
$ tofu planaws_instance.cerberus: Refreshing state... [id=i-9d394a982f158e887]An execution plan has been generated and is shown below.Resource actions are indicated with the following symbols: ~ update in-place # aws_instance.cerberus will be updated in-place ~ resource "aws_instance" "cerberus" { ami = "ami-06178cf087598769c" ~ instance_type = "m5.large" -> "t3.micro" // ... other attributes }
This plan highlights an in-place update to apply the new instance type without destroying the instance.
OpenTofu uses these dependencies to, for example, create the database instance before the web instance, or destroy the web instance before the database.
Avoid storing SSH keys, passwords, or secrets in your state file.
Remote Backends
Use a secure remote backend (S3, GCS, Azure Blob) to share and lock your state file.
State Inspection & Tools
Manipulate or inspect state only with OpenTofu commands (e.g., tofu state list, tofu state mv). Do not edit the state file manually.
Version Control
Add terraform.tfstate and terraform.tfstate.backup to .gitignore to prevent accidental commits.
Configure remote backends to enable state locking and consistency. This prevents multiple users from making concurrent changes.
OpenTofu’s state file is the backbone of reliable, idempotent infrastructure as code. Proper management—using secure backends, avoiding manual edits, and staying alert to drift—ensures predictable deployments and clean collaboration.