Skip to main content
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.

What Is the OpenTofu State?

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:
Apply the infrastructure:
Verify the state files in your directory:
Inspect the JSON structure:
OpenTofu treats this state file as the single source of truth for commands like tofu plan and tofu apply.

State Refresh on plan and apply

Before creating an execution plan, OpenTofu refreshes the state by comparing it to real-world infrastructure:
This ensures that any drift is detected before making changes.

Disabling State Refresh

You can bypass the refresh step with -refresh=false, though it’s generally not recommended:
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.

Example: Updating a Resource In-Place

Suppose you update the instance type from m5.large to t3.micro:
Generate a new plan:
This plan highlights an in-place update to apply the new instance type without destroying the instance.

State Dependencies

OpenTofu tracks inter-resource dependencies to determine correct creation and destruction order. For example:
In terraform.tfstate, the web instance includes a dependencies array:
OpenTofu uses these dependencies to, for example, create the database instance before the web instance, or destroy the web instance before the database.

Best Practices for State Management

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.

Watch Video