Terraform and OpenTofu

Provision cloud resources declaratively with HCL, providers, state and modules, using the most widely adopted IaC tool.

Intermediate · about 18 hours · difficulty 3/5

Learn first: Infrastructure as Code Principles

Terraform is the default IaC tool in most job descriptions, and OpenTofu is its open-source fork with the same language and workflow. Learn one and you know both.

The workflow

terraform init downloads providers, plan shows a diff between code and reality, apply makes it so, destroy removes it. Always read the plan: a line starting with -/+ means replace, which for a database means data loss.

Language building blocks

  • Providers talk to APIs (aws, azurerm, google, kubernetes, github, cloudflare).
  • Resources create things; data sources read things that already exist.
  • Variables, locals and outputs make code reusable.
  • count and for_each create many similar resources; prefer for_each with stable keys.
  • Modules package resources into reusable units with inputs and outputs. Pin module and provider versions.

State

Terraform records what it manages in a state file. In a team, store it in a remote backend (S3 with locking, Azure Storage, GCS, or HCP Terraform) so two people cannot apply at once. State can contain secrets: encrypt it and restrict access. Use terraform import or import blocks to adopt existing resources, and moved blocks to refactor without destroying.

Structuring real projects

Split state by environment and by layer (network, data, apps) to keep plans fast and blast radius small. Run fmt, validate, tflint and a security scanner (Checkov, Trivy) in CI, and post the plan on the pull request.

Good enough to move on: you can write a module used by two environments, keep state in a locked remote backend, import an existing resource, and explain why a plan wants to replace something.

Key concepts

  • init, plan, apply, destroy
  • Providers, resources and data sources
  • Variables, locals and outputs
  • count and for_each
  • Modules and version pinning
  • Remote state and locking
  • import and moved blocks
  • Workspaces vs directory per environment
  • tflint, Checkov and plan in CI
  • OpenTofu compatibility

Other options for this step

  • Pulumi: Infrastructure as code written in general-purpose languages like TypeScript, Python or Go, with real loops, functions and tests.
  • CloudFormation, CDK and Bicep: The cloud providers' own IaC tools: AWS CloudFormation and CDK, and Azure Bicep, deeply integrated with a single cloud.

Mini project

Rebuild your two-tier cloud app in Terraform: a network module and an app module, dev and prod using different variable files, state in a remote backend with locking, and a CI job that posts the plan on each pull request.

Check yourself

What problem does state locking solve, and what could go wrong if two engineers applied from their laptops at the same time without it?

Free resources