This article explains how to manage the OpenTofu state file using various commands for safe resource handling.
Managing the OpenTofu state file directly is error-prone. Instead, use the tofu state subcommands to list, inspect, rename, pull, remove, and push resources safely.
Command
Description
state show
Display detailed attributes of a resource in state
state list
List all resource addresses or filter by pattern
state mv
Rename or move resources within or between state files
state pull
Download remote state to your local machine
state rm
Remove a resource from the state without destroying it
tofu state mv \ aws_dynamodb_table.state-locking \ aws_dynamodb_table.state-locking-dbMove "aws_dynamodb_table.state-locking" to "aws_dynamodb_table.state-locking-db"Successfully moved 1 object(s).
Update configuration:
Copy
Ask AI
resource "aws_dynamodb_table" "state-locking-db" { name = "state-locking" billing_mode = "PAY_PER_REQUEST" hash_key = "LockID" attribute { name = "LockID" type = "S" }}
When you need Terraform/OpenTofu to stop managing a resource—but keep it running in the cloud—use:
Copy
Ask AI
tofu state rm aws_s3_bucket.finance-2020922
Sample output:
Copy
Ask AI
Acquiring state lock. This may take a few moments...Removed aws_s3_bucket.finance-2020922Successfully removed 1 resource instance(s).Releasing state lock. This may take a few moments...
state rm only removes the resource from the Terraform/OpenTofu state—it does not delete the actual resource in your cloud provider.
After removing, delete the corresponding resource block in your configuration.
Use this command to replace the remote state with a local file. OpenTofu will refuse if the lineages don’t match:
Copy
Ask AI
tofu state push ./randomstate/terraform.tfstate# Failed to write state: cannot import state with lineage "1dc19ee8-..." over unrelated state with lineage "6d167ba6-..."
To force an overwrite (use with extreme caution):
Copy
Ask AI
tofu state push --force ./randomstate/terraform.tfstate
Forcing a push can irreversibly corrupt your remote state. Always back up your existing state before using --force.