Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Terraform Best Practices, Pitfalls and OpenTofu

A practical checklist of Terraform best practices: structure, state, naming, versions, secrets and review habits, plus common mistakes and how OpenTofu differs from Terraform.

You have now seen Terraform from the language up to multi-environment pipelines. This lesson gathers the lessons that experienced teams learn the hard way: how to structure code, protect state, keep plans readable, avoid classic mistakes and choose between Terraform and its open-source fork OpenTofu. Use it as a review checklist for your own projects.

Structure and style

  • Small states. Split by lifecycle and ownership: network, data, app, observability. A state that mixes a VPC and a deployment that changes ten times a day makes every plan slow and risky (Remote State).
  • Thin roots, fat modules. Root modules wire things together; reusable logic lives in versioned modules (Module Design).
  • Consistent naming. Resource names in snake_case, this for the single main resource in a module, descriptive names otherwise (aws_security_group.web). Do not repeat the type in the name (aws_instance.web_instance).
  • Standard files. main.tf, variables.tf, outputs.tf, versions.tf, and locals.tf for computed values.
  • Format and validate on every commit. terraform fmt removes style debates.
  • Comments explain why, not what. The code already says what.

State and safety

  • Remote backend with encryption, versioning and locking; never a local state in a team.
  • One writer: the pipeline. Humans get read access.
  • Back up state before surgery (terraform state pull > backup.json).
  • Use prevent_destroy for databases and similar, and deletion_protection where the provider supports it.
  • Never edit state JSON by hand; use moved, import, removed and state commands (State Commands).
  • Do not put secrets in tfvars committed to Git; remember they land in state.

Versions and reproducibility

  • Pin required_version and provider versions with ~>; commit .terraform.lock.hcl.
  • Pin module versions (tags or exact versions); upgrade through reviewed pull requests.
  • Use the same Terraform version locally and in CI (.terraform-version with tfenv or mise).
  • Upgrade providers deliberately: read the changelog, run a plan, apply in dev first.

Plans and reviews

  • Review the plan, not only the diff of the code.
  • Treat -/+ (replace) and - (destroy) as red flags that need an explanation in the PR.
  • Prefer many small changes to one huge apply.
  • Keep -target for emergencies; every use leaves state in a partial condition.
Python Review checklist scoring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  1. Using count over lists of distinct objects. Removing one item reshuffles the rest. Use for_each with stable keys (count and for_each).
  2. Hard-coding values that already exist as references. Write aws_vpc.main.id, not "vpc-0abc"; references create dependencies and survive replacement.
  3. Overusing depends_on. It hides real relationships and can force replacements. Prefer references.
  4. Putting providers inside reusable modules. Pass configuration from the root.
  5. Ignoring the lock file. Without it, a teammate may get a newer provider and a different plan.
  6. Giant locals and dynamic blocks. Cleverness costs readability. If a reader needs ten minutes to understand a loop, write it more plainly or split the module.
  7. Running apply -auto-approve from a laptop. Put approval in the pipeline.
  8. Not planning for secrets in state. Encrypt the backend, limit access, use ephemeral values where available.
  9. Letting drift pile up. Run scheduled plans (Drift Detection).
  10. No tests at all. At least validate, lint and scan; add policy and plan tests as the codebase grows (Testing and Policy).

When Terraform is not the right tool

  • Fast-changing application deployments: use your CI/CD and a GitOps tool for rollouts; use Terraform for the platform beneath.
  • Per-server configuration (packages, files, services): use image builds (Packer) or configuration management (Ansible), not provisioners. HashiCorp itself calls provisioners a last resort.
  • Complex imperative logic: if you fight HCL, consider a provider or small external program (or a general-purpose-language tool such as Pulumi or the CDK for Terraform), accepting the trade-offs.

OpenTofu

OpenTofu is a fork of Terraform created in 2023 after HashiCorp changed Terraform's license from MPL 2.0 to the Business Source License. It is governed by the Linux Foundation and licensed under MPL 2.0. The binary is tofu, and for the language and workflow in this tutorial it is a drop-in replacement: tofu init, tofu plan, tofu apply, the same HCL, providers and state format (up to the versions where they diverged).

What differs in practice:

Topic Terraform OpenTofu
License BSL 1.1 (source-available) MPL 2.0 (open source)
Registry registry.terraform.io registry.opentofu.org (mirrors most providers)
State encryption Rely on backend encryption Built-in client-side state and plan encryption
Provider for_each Not available Provider configurations can use for_each (1.9+)
Other features Ephemeral resources, terraform test additions Early variable evaluation in backend and module sources, exclude flag, own test improvements

The features keep evolving, so check each project's release notes before relying on a difference. Migration from Terraform 1.5 to 1.9 is usually just a binary swap and tofu init; later Terraform versions may use features OpenTofu lacks, so test first. The CI examples in this chapter work with OpenTofu by replacing the setup action and the command name.

Python Command translator: Terraform to OpenTofu

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Where to go from here

Keep practicing with small real projects: a static site, a VPC, a DNS zone. Read provider changelogs, contribute fixes to modules you depend on and explore adjacent tools: Terragrunt for DRY multi-environment layouts, Packer for images, Ansible for configuration, Kubernetes and GitOps for application delivery, and policy engines such as OPA.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why split a large infrastructure into several states?

    States grouped by lifecycle and owner are safer and quicker to plan.
  2. 2. Which is a classic cause of unexpected resource replacements in a counted list?

    count identifies by position; for_each uses stable keys.
  3. 3. What is OpenTofu?

    It started in 2023 from the last MPL-licensed Terraform code and uses the tofu binary.
  4. 4. What do provisioners get used for, according to best practice?

    Provisioners are hard to reason about and not part of the plan.

Summary

  • Split states by lifecycle, keep roots thin and modules versioned, name consistently and comment the why.
  • Protect state: remote, encrypted, locked, written only by the pipeline.
  • Pin Terraform, providers and modules; commit the lock file; review plans and treat replacements and destroys as red flags.
  • Avoid the common mistakes: count over lists, unnecessary depends_on, providers in modules, secrets in Git, no tests.
  • OpenTofu is a drop-in alternative for most workflows; check release notes for differences.

Next: Practice: Exercises with Solutions