Skip to main content
In this step-by-step guide, you’ll master OpenTofu state commands to manage your Terraform state file. We’ll cover how to:
  • List resources in state
  • Inspect resource attributes
  • Retrieve specific IDs
  • Remove resources from state
  • Work with a remote S3 backend
  • Rename resources in both configuration and state

Table of State Commands


1. Inspecting State Resource Names

First, navigate to your project directory and list the tracked resources:
You should see output similar to:
These correspond to the resource blocks in main.tf:
Any resource not listed (e.g., super_pets) is not managed in the current state.

2. Showing Resource Attributes

To view every attribute stored for a single resource, run:
Example output:
The tofu state show command only reads the state—your infrastructure remains unchanged.

3. Retrieving the ID of a Resource

If you need a resource’s unique identifier (e.g., to reference it elsewhere), use:
Look for the id = line. It might appear as:

4. Removing a Resource from State

To stop managing a resource without destroying it, remove its block from main.tf and then:
Sample session:
Verify removal:
tofu state rm does not delete actual resources. It only detaches them from Terraform’s state.

5. Working with Remote State (S3 Backend)

In /root/OpenTofu/project/super-pets/, configure an S3 backend in tofu.tf:
Define two random_pet resources in main.tf:
And variables:
Since the state is stored remotely, all tofu state commands will interact with S3. To confirm:
Output:

6. Finding the ID of super_pet_2

Similarly, retrieve the ID for the second pet:
Example:

7. Renaming a Resource in Config and State

To rename random_pet.super_pet_1 to random_pet.ultra_pet:
  1. Update main.tf:
  2. Move it in the state:
  3. Verify:

Thank you for following this tutorial on OpenTofu state management!

Watch Video

Practice Lab