Infrastructure as Code2 min read183 lines

Learning state

Track this guide

Saved in this browser only. No account required.

OpenTofu Infrastructure as Code Master Class

Engineering-grade reference manual for OpenTofu infrastructure operations: init, format, validate, plan, state inspection, workspaces, modules, providers, and safe apply workflows.

Overview

OpenTofu is an open-source infrastructure as code tool compatible with Terraform workflows. Use it to define cloud and platform infrastructure declaratively, review planned changes, and keep state controlled. Operators should treat state and apply actions as governed production boundaries.

Project Setup

Show OpenTofu version:

tofu version

Initialize providers and modules:

tofu init

Upgrade providers intentionally:

tofu init -upgrade

Format configuration:

tofu fmt -recursive

Validate configuration:

tofu validate

Planning and Review

Generate a plan:

tofu plan

Save a plan file for review:

tofu plan -out=tfplan

Show a saved plan:

tofu show tfplan

Show a saved plan as JSON:

tofu show -json tfplan

Apply an approved plan:

tofu apply tfplan

Destroy requires explicit approval:

tofu destroy

State Operations

List resources in state:

tofu state list

Show one resource:

tofu state show RESOURCE_ADDRESS

Pull state for inspection:

tofu state pull

Move a state address after review:

tofu state mv OLD_ADDRESS NEW_ADDRESS

Remove a resource from state only after review:

tofu state rm RESOURCE_ADDRESS

Workspaces and Environments

List workspaces:

tofu workspace list

Show current workspace:

tofu workspace show

Create a workspace:

tofu workspace new ENVIRONMENT

Select a workspace:

tofu workspace select ENVIRONMENT

Modules and Providers

List providers:

tofu providers

Lock providers for reproducible automation:

tofu providers lock

Inspect module tree:

tofu providers schema -json

Safe Change Workflow

  1. Pull latest code and confirm workspace.
  2. Run tofu fmt -recursive.
  3. Run tofu validate.
  4. Run tofu plan -out=tfplan.
  5. Review additions, changes, destroys, and replacements.
  6. Apply only the reviewed plan file.
  7. Capture output and re-run read-only verification.

CI Validation

Run a no-mutation validation sequence:

tofu fmt -check -recursive
tofu init -backend=false
tofu validate

Run a plan in automation when backend credentials are available:

tofu init
tofu plan -out=tfplan