Skip to Content
Mengty Learns
IaC

OpenTofu First Project

Write and run a self-contained OpenTofu project using only the local and random providers with variables and outputs.

tutorialbeginnerTested with opentofu 1.8+ (CI-validated)Updated Nov 26, 2026

TL;DR

You can learn OpenTofu's full init → plan → apply → output → destroy lifecycle locally without any cloud account by combining the hashicorp/random and hashicorp/local providers.

Why it exists

Learning Infrastructure as Code directly against a cloud account risks surprise bills and credential setup friction. Using local and random providers lets you practice declarative resources, input variables, outputs, and state management on your laptop and in CI.

Mental model

An OpenTofu root module splits responsibilities cleanly across four files:

  1. versions.tf — pins OpenTofu (>= 1.8.0) and provider versions (hashicorp/local, hashicorp/random).
  2. variables.tf — declares typed inputs (project_name, environment, output_dir) with defaults.
  3. main.tf — declares desired resources (random_pet.slug and local_file.manifest), which OpenTofu orders automatically via the dependency graph.
  4. outputs.tf — exports values (pet_slug, manifest_path) after apply.
Run it: labs/tofu-local-file

Self-contained OpenTofu lab using local and random providers with variables, outputs, and .gitignore.

tofu -chdir=labs/tofu-local-file init -backend=false && tofu -chdir=labs/tofu-local-file validate

Do it

Run the full lifecycle inside labs/tofu-local-file:

cd labs/tofu-local-file

# 1. Download providers
tofu init

# 2. Check formatting and configuration syntax
tofu fmt -check
tofu validate

# 3. Preview and apply with a variable override
tofu plan -var="environment=dev"
tofu apply -auto-approve -var="environment=dev"

# 4. Inspect outputs and the generated JSON file
tofu output
cat generated/mengty-learns-dev.json

# 5. Clean up managed resources
tofu destroy -auto-approve -var="environment=dev"

Gotchas

  • Committing .terraform/ or *.tfstate: Provider binaries are large and platform-specific, and state files belong in a remote backend or .gitignore for local labs.
  • Skipping tofu fmt -check: CI checks formatting with tofu fmt -check -recursive; run tofu fmt before committing .tf changes.
  • Unpinned providers: Without version constraints in required_providers, tofu init can pull a new major provider version and break CI.

Production checklist

  • Pin required_version and required_providers in versions.tf.
  • Document every variable and output with a description.
  • Keep .terraform/, *.tfstate, and generated artifacts in .gitignore.
  • Run tofu fmt -check, tofu validate, and tflint in CI.

Check yourself

Check Yourself

1. Which command downloads the local and random provider plugins before you can run tofu validate?

2. How does OpenTofu know to create random_pet.slug before local_file.manifest?

Sources