DEV Community

The Practical Developer
The Practical Developer

Posted on Originally published at practicaldevblog.blogspot.com

OpenTofu Tutorial: Infrastructure as Code, Open Source

Quick answer

OpenTofu is the open source fork of Terraform for infrastructure as code: you describe servers, files, and services in configuration files, and the tool creates, updates, and removes them for you. This post installs OpenTofu 1.13.10 on Linux, builds a small shop setup with a local backend, and shows plan catching a changed Lahore total before anything is applied.

A spreadsheet, a console, and no record of either

A small shop keeps its weekly orders in a spreadsheet edited by hand. One of them overwrites a total, another works from an old copy, and by Friday nobody can say which numbers are right. Infrastructure drifts the same way when it is built by clicking around in a console: a server here, a bucket there, and no record of what was meant to exist. Infrastructure as code fixes the drift by writing the intended state down in files that can be reviewed, versioned, and applied again. OpenTofu is one way to do it: the community fork of Terraform, built after HashiCorp changed Terraform's licence in 2023. This post builds a first OpenTofu project on your own machine.

What I would check before using it

My first check is the licence and who runs it. OpenTofu is released under the Mozilla Public License 2.0 and governed as a community project under the Linux Foundation. The fork exists because Terraform moved to a licence that is not open source, and teams that wanted to stay on open source tooling needed somewhere to go. If your company needs a support contract, check what commercial support exists first.

My second check is how far Terraform knowledge carries. OpenTofu started as a fork, so most Terraform files work as they are, and existing state can be migrated. The Terraform Explained: Infrastructure as Code Without the Guesswork post covers the same workflow from the Terraform side: write, plan, apply, and let the state file remember what exists. Test any migration on a copy first.

My third check is state. By default OpenTofu keeps state in terraform.tfstate. Lose it and OpenTofu forgets what it built; edit it by hand and the next plan will be wrong. For a solo learner the local backend is fine; for a team, move state to a shared backend with locking. The NGINX Explained: The Server in Front of Your App post shows the kind of server this workflow eventually manages.

My fourth check is the provider ecosystem. OpenTofu downloads providers from its own registry, and the two used here, hashicorp/local and hashicorp/null, cover files and simple shell steps without any cloud account. Before adopting it, check the providers you need are in the OpenTofu registry.

My verdict, as judgement: adopt OpenTofu for new infrastructure-as-code work when staying on open source tooling matters to you, starting with the local backend. The recommendation flips if your team already pays for Terraform Cloud workspaces, or if a provider you depend on is only maintained for Terraform.

A shop report, a plan, and a changed Lahore total

The demo manages a small shop's weekly orders. Karachi totals Rs 16,450, Lahore Rs 22,100, and Islamabad Rs 18,300, a grand total of Rs 56,850. OpenTofu writes those numbers into a report file and announces the total. The Docker Explained: Containers Without the Headache post covers the container side of the same shop.

First, the install on Linux, from the OpenTofu releases page on GitHub:

$ curl -L -o tofu.tar.gz https://github.com/opentofu/opentofu/releases/download/v1.13.10/tofu_1.13.10_linux_amd64.tar.gz
$ tar --no-same-owner -xzf tofu.tar.gz
$ ./tofu version
OpenTofu v1.13.10
on linux_amd64
Enter fullscreen mode Exit fullscreen mode

Here is the whole project, one file called main.tf: it pins the version, asks for the two providers, totals the orders, writes the report, and announces the total:

terraform {
  required_version = ">= 1.6.0"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
    null = {
      source  = "hashicorp/null"
      version = "~> 3.2"
    }
  }
}

variable "orders_by_city" {
  description = "Weekly order totals in rupees, by city"
  type        = map(number)
  default = {
    Karachi   = 16450
    Lahore    = 22100
    Islamabad = 18300
  }
}

locals {
  grand_total = sum(values(var.orders_by_city))
}

resource "local_file" "shop_report" {
  filename = "${path.module}/shop-report.txt"
  content  = <<-EOT
    Weekly shop report
    Karachi: Rs ${var.orders_by_city["Karachi"]}
    Lahore: Rs ${var.orders_by_city["Lahore"]}
    Islamabad: Rs ${var.orders_by_city["Islamabad"]}
    Grand total: Rs ${local.grand_total}
  EOT
}

resource "null_resource" "announce" {
  triggers = {
    grand_total = local.grand_total
  }

  provisioner "local-exec" {
    command = "echo Report ready: grand total Rs ${local.grand_total}"
  }
}

output "grand_total" {
  value = local.grand_total
}
Enter fullscreen mode Exit fullscreen mode

The first thing that went wrong was my own impatience: I ran apply before init, and OpenTofu refused, because the providers were not downloaded:

$ ./tofu apply -auto-approve
Error: Inconsistent dependency lock file

The following dependency selections recorded in the lock file are
inconsistent with the current configuration:
  - provider registry.opentofu.org/hashicorp/local: required by this configuration but no version is selected
  - provider registry.opentofu.org/hashicorp/null: required by this configuration but no version is selected

To make the initial dependency selections that will initialize the
dependency lock file, run:
  tofu init
Enter fullscreen mode Exit fullscreen mode

The fix is the command the error names: init downloads the providers, verifies their signatures, and records the exact versions in a lock file:

$ ./tofu init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/local versions matching "~> 2.5"...
- Finding hashicorp/null versions matching "~> 3.2"...
- Installing hashicorp/null v3.3.2...
- Installing hashicorp/local v2.9.1...
- Installed hashicorp/local v2.9.1 (signed, key ID 0C0AF313E5FD9F80)
- Installed hashicorp/null v3.3.2 (signed, key ID 0C0AF313E5FD9F80)

OpenTofu has been successfully initialized!
Enter fullscreen mode Exit fullscreen mode

Now plan, which shows what would happen without changing anything; the long hash lines are left out here:

$ ./tofu plan

OpenTofu used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create

OpenTofu will perform the following actions:

  # local_file.shop_report will be created
  + resource "local_file" "shop_report" {
      + content              = <<-EOT
            Weekly shop report
            Karachi: Rs 16450
            Lahore: Rs 22100
            Islamabad: Rs 18300
            Grand total: Rs 56850
        EOT
      + filename             = "./shop-report.txt"
      ...
    }

  # null_resource.announce will be created
  + resource "null_resource" "announce" {
      + id       = (known after apply)
      + triggers = {
          + "grand_total" = "56850"
        }
    }

Plan: 2 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + grand_total = 56850
Enter fullscreen mode Exit fullscreen mode

Two to add, nothing to change, nothing to destroy. Apply runs the same plan:

$ ./tofu apply -auto-approve
null_resource.announce: Creating...
null_resource.announce: Provisioning with 'local-exec'...
null_resource.announce (local-exec): Executing: ["/bin/sh" "-c" "echo Report ready: grand total Rs 56850"]
null_resource.announce (local-exec): Report ready: grand total Rs 56850
null_resource.announce: Creation complete after 0s [id=7126519472157824489]
local_file.shop_report: Creating...
local_file.shop_report: Creation complete after 0s [id=828df46c7f8496f58de03fd48ea52af42342774c]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:

grand_total = 56850
Enter fullscreen mode Exit fullscreen mode

The report file on disk matches the plan:

$ cat shop-report.txt
Weekly shop report
Karachi: Rs 16450
Lahore: Rs 22100
Islamabad: Rs 18300
Grand total: Rs 56850
Enter fullscreen mode Exit fullscreen mode

Then the change that proves the workflow: a late Lahore order arrives, so the Lahore total goes from 22100 to 23400. Plan reads the state file and spots the difference:

$ ./tofu plan
local_file.shop_report: Refreshing state... [id=828df46c7f8496f58de03fd48ea52af42342774c]
null_resource.announce: Refreshing state... [id=7126519472157824489]

  # local_file.shop_report must be replaced
-/+ resource "local_file" "shop_report" {
      ~ content              = <<-EOT # forces replacement
            Weekly shop report
            Karachi: Rs 16450
          - Lahore: Rs 22100
          + Lahore: Rs 23400
            Islamabad: Rs 18300
          - Grand total: Rs 56850
          + Grand total: Rs 58150
        EOT
      ...
    }

Plan: 2 to add, 0 to change, 2 to destroy.

Changes to Outputs:
  ~ grand_total = 56850 -> 58150
Enter fullscreen mode Exit fullscreen mode

Apply replaces both resources, because the file content and the trigger both changed:

$ ./tofu apply -auto-approve
local_file.shop_report: Destroying... [id=828df46c7f8496f58de03fd48ea52af42342774c]
local_file.shop_report: Destruction complete after 0s
local_file.shop_report: Creation complete after 0s [id=10f63e904e88c6e77a3455e3676fbae6450d88eb]
null_resource.announce: Destroying... [id=7126519472157824489]
null_resource.announce: Creation complete after 0s [id=189917406450849425]

Apply complete! Resources: 2 added, 0 changed, 2 destroyed.

Outputs:

grand_total = 58150

$ cat shop-report.txt
Weekly shop report
Karachi: Rs 16450
Lahore: Rs 23400
Islamabad: Rs 18300
Grand total: Rs 58150
Enter fullscreen mode Exit fullscreen mode

The state file lists exactly two resources:

$ ./tofu state list
local_file.shop_report
null_resource.announce
Enter fullscreen mode Exit fullscreen mode

Terminal output showing OpenTofu 1.13.10 installed on Linux, tofu init downloading the local and null providers, tofu plan showing 2 to add, and the final apply printing grand total Rs 58,150.

Common mistakes and how to fix them

First, running apply before init. The symptom is the error "Inconsistent dependency lock file", with a note that no provider version is selected. The fix is tofu init, which downloads the providers and writes the lock file.

Second, editing terraform.tfstate by hand. The symptom is a plan that proposes recreating resources that already exist, because the state no longer matches reality. The fix is to restore the state file from a backup and never edit it directly; use tofu state commands when state needs surgery.

Third, running tofu in the wrong folder. The symptom is an error saying there are no configuration files in the directory. The fix is to change into the folder that holds main.tf, or pass the folder with -chdir.

Fourth, changing a local_file and expecting an update in place. The symptom is a plan showing "-/+ destroy and then create replacement" with the note "forces replacement". The fix is to expect the replacement: a file's content is part of its identity, so OpenTofu deletes the old file and writes a new one, as the demo shows.

Frequently Asked Questions

Is OpenTofu the same as Terraform?

No, but it started as a fork of Terraform, so most Terraform files run on OpenTofu without changes. The projects are separate now.

Is OpenTofu free?

Yes. OpenTofu is open source under the Mozilla Public License 2.0, and the binary is free for Linux, macOS, and Windows.

Do I need a cloud account to learn OpenTofu?

No. The demo here uses only the local backend and two providers that run on your own machine, so you can learn without an account or a bill.

Can I move an existing Terraform project to OpenTofu?

In most cases, yes: OpenTofu supports migrating Terraform state. Test on a copy first, and keep a backup until the migrated project plans cleanly.

Where does OpenTofu keep its state?

By default it writes terraform.tfstate in the project folder. Keep it safe and backed up: it is the only record of what OpenTofu manages.

What to remember

  • OpenTofu is the open source fork of Terraform, under the Mozilla Public License 2.0.
  • Run tofu init first; apply before init fails with an inconsistent lock file error.
  • The local backend keeps state in terraform.tfstate, the source of truth.
  • tofu plan shows the change before it happens; the demo caught Lahore changing from Rs 22,100 to Rs 23,400.
  • Changing a local_file forces a replacement, so expect destroy and create.

Where this leaves you

The demo shrank a real workflow to files on one machine: install, init, plan, apply, change, plan again, apply again. Nothing in it needed a cloud account, and every step left a record to check, from the lock file to the state file to the report on disk. That is the habit OpenTofu teaches, and it scales to servers the same way it scales to a shop report. Install version 1.13.10, copy main.tf from this post, and run the same commands against your own numbers.

Further reading

Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

Top comments (0)