What it does
OpenTofu started in 2023 when Terraform changed its licence (BSL). It is run by the Linux Foundation and stays open source (MPL). Most Terraform code and providers work without changes: replace terraform with tofu.
Extra features: state encryption built in, early variable evaluation, and its own registry (registry.opentofu.org).
How to write it
tofu COMMAND [OPTIONS]Main parts
Commands
init- Download providers and modules, set up the backend.
fmt/validate- Format code / check syntax.
plan[-out FILE]- Show the changes.
apply[FILE]- Make the changes.
destroy- Delete everything in the state.
output[NAME]- Show outputs.
statelist|show|mv|rm- Work with the state.
importADDRID- Take an existing resource into the state.
workspacelist|new|select- Several states for one config.
test- Run
.tftest.hcltests. providerslock- Write provider checksums for all platforms.
Options 9
Most used
Options
Nothing matches this filter.
Examples 11
$ run as a normal user# run as root (or with sudo)
1The normal workflow
tofu init tofu fmt -recursive && tofu validate tofu plan -out tfplan tofu apply tfplan2Move a Terraform project to OpenTofu
terraform version tofu init -upgrade tofu planThe plan should show no changes. Make a backup of the state first.
3Encrypt the state with a key from an environment variable
cat encryption.tf terraform { encryption { key_provider "pbkdf2" "main" { passphrase = var.state_passphrase } method "aes_gcm" "main" { keys = key_provider.pbkdf2.main } state { method = method.aes_gcm.main } } }4Variables per environment
tofu plan -var-file envs/prod.tfvars -out tfplan5Find drift
tofu plan -refresh-only6Read an output in a script
tofu output -raw lb_ip7Import an existing resource
tofu import azurerm_resource_group.main /subscriptions/SUB/resourceGroups/rg-shop8List and move state
tofu state list tofu state mv azurerm_storage_account.old azurerm_storage_account.logs9Run tests
tofu test10Lock providers for Linux and Mac
tofu providers lock -platform=linux_amd64 -platform=darwin_arm6411In CI
tofu init -input=false tofu plan -input=false -no-color -out tfplan
Nothing matches this filter.
Watch out
- Do not run
terraformandtofuon the same state at the same time; choose one tool per project. - New Terraform-only features (after 1.6) may not exist in OpenTofu, and the other way.
Files
*.tf / *.tofu- The code (
.tofufiles are read only by OpenTofu). .terraform.lock.hcl- Provider versions and checksums.
Tips to remember
- Learn with Terraform docs (more examples); the commands are the same.
Exit codes
0 | OK (plan: no changes). |
1 | Error. |
2 | plan -detailed-exitcode: there are changes. |