Before changing Terraform state, save a copy you can restore. `terraform state pull` retrieves the latest state from the configured backend and writes it to standard output. Redirect that output to a file for a backup, or inspect it directly. section 6.5.1
terraform state pull > my_backup.tfstate
This command saves the pulled state as `my_backup.tfstate` before any state changes are made. section 6.5.1
A saved copy can be restored with `terraform state push my_backup.tfstate`. Push rejects a state with a different lineage or a lower serial than the backend state; reverting to an older backup may require `terraform state push -force my_backup.tfstate` to bypass those protections. section 6.5.1
Pulling state is also the first step in a last-resort manual repair: pull it locally, edit it, then push it back. Prefer CLI or code-driven changes when possible. Before a manual edit, keep a backup; afterward, validate the JSON and compare it with the backup. A malformed file may be unreadable, while an accidentally removed resource or relationship may cause Terraform to attempt to recreate an existing resource. section 6.5.4
Listing 11.14 Tofu.state method
import tempfile
class Tofu:
def state(self) -> State: #1
pull_res = self._run(["state", "pull"]) #2
state_pull = pull_res.json() #3
with tempfile.NamedTemporaryFile(suffix=".tfstate") as tmp: #4
tmp.write(pull_res.stdout.encode()) #5
tmp.seek(0) #6
show_res = self._run(["show", "-json", tmp.name]) #7
return State( #8
data=show_res.json(), #9
serial=state_pull["serial"], #10
lineage=state_pull["lineage"], #10
)
For programmatic inspection, this wrapper pulls state, saves it to a temporary `.tfstate` file, and runs `terraform show -json` on that file. It retains `serial` and `lineage` from the pulled state because the `show` output omits them. section 11.1.6
The pulled state is Terraform’s complete internal state representation, but it is not considered part of the machine-readable UI and is less well documented. For tooling, `terraform show -json` provides a defined JSON output; combine it with the pulled state when serial and lineage are needed. section 11.1.6
