Terraform and OpenTofu: plan, apply and state

Intermediate · 30 min

Terraform's loop: describe resources in HCL, init fetches providers, plan previews the diff, apply makes it real, and state links your code to the cloud.

Before thisInfrastructure as code: declarative vs imperative

DevOps Directive · 158 min · from 28:32

Terraform and OpenTofu: plan, apply and state

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DevOps DirectiveReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • You describe resources in HCL. Providers are plugins that turn those descriptions into calls to a cloud's API.
  • init downloads providers and pins them in a lock file. plan compares your code with reality and prints the exact changes. apply makes them and records the result.
  • The state file maps each resource in your code to the real object it created, so Terraform knows what it owns and what to change or delete.
  • State often contains secrets in plain text and must never be hand-edited. Use the state commands, or moved, removed and import blocks.
  • OpenTofu is an open-source fork of Terraform from 2023. It uses the same language, workflow and state format, and the two differ mainly in license, governance and some newer features.

From idea to tool

The last lesson built a toy declarative tool that compared desired state with a JSON file of servers. Real infrastructure is messier: hundreds of resource types across clouds, each with its own API, IDs assigned by the provider, and dependencies such as “the server needs the network to exist first”. Terraform, and its open-source fork OpenTofu, are the most widely used tools for that job. The commands are terraform and tofu, and everything in this lesson applies to both.

The pieces

You write HCL, HashiCorp Configuration Language, in .tf files. A small example, written from the AWS provider docs. I did not run it, since there is no Terraform or cloud account on this machine:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = "eu-west-1"
}

resource "aws_s3_bucket" "notes_uploads" {
  bucket = "notes-uploads-example-1234"
}

resource "aws_s3_bucket_versioning" "notes_uploads" {
  bucket = aws_s3_bucket.notes_uploads.id
  versioning_configuration {
    status = "Enabled"
  }
}

A provider is a plugin that knows one API, here AWS. A resource is one thing the provider manages, with a type (aws_s3_bucket) and a local name (notes_uploads). The reference aws_s3_bucket.notes_uploads.id does two jobs: it passes the bucket’s ID, and it tells Terraform the versioning resource depends on the bucket, so it is created second. Terraform builds a dependency graph from these references and runs independent changes in parallel.

Providers are published to a public registry with a plain HTTP API. I asked it about the AWS provider, and HashiCorp’s update service about Terraform itself:

$ curl -s https://registry.terraform.io/v1/providers/hashicorp/aws | jq '{namespace, name, version, published_at, downloads}'
{
  "namespace": "hashicorp",
  "name": "aws",
  "version": "6.74.0",
  "published_at": "2026-11-23T23:04:55Z",
  "downloads": 8653342044
}
$ curl -s https://checkpoint-api.hashicorp.com/v1/check/terraform | jq '{product, current_version}'
{
  "product": "terraform",
  "current_version": "1.17.2"
}

The ~> 6.0 constraint above allows any 6.x release, so it would pick up 6.74.0 today and never jump to 7.0 on its own.

The loop: init, plan, apply

terraform init downloads the providers your code needs and writes .terraform.lock.hcl, recording the exact versions and checksums chosen. Commit that file, so a teammate’s laptop and the CI runner use the same provider builds.

terraform plan is the declarative diff. It reads your code, asks the provider for the current real state of every resource it manages, and prints what it would do. Each line starts with a symbol: + create, ~ update in place, - destroy, and -/+ destroy and re-create. That last one deserves attention, because some attributes cannot be changed on a live object. Renaming a bucket or changing a database’s engine version can mean replacing it, data and all. Read every plan for unexpected - and -/+ lines.

terraform apply shows the plan again, asks for confirmation, and makes the API calls. In CI you usually save the plan with terraform plan -out=tfplan, have a person review it, and run terraform apply tfplan so that exactly the reviewed plan is applied.

terraform destroy deletes everything this configuration manages. You will rarely want it outside of temporary environments.

State: Terraform’s memory

After apply, Terraform writes state, by default to terraform.tfstate, a JSON file. It records, for each resource address such as aws_s3_bucket.notes_uploads, the real object’s ID and its attributes as last seen.

Why keep a file at all, when the cloud can be queried? Because the cloud does not know which bucket belongs to which line of your code. My toy in the last lesson cheated by owning the whole fake cloud. A real AWS account holds resources made by other teams, other tools and the console. State is how Terraform knows “this bucket is mine, it is notes_uploads, and if that block disappears from the code, I should delete it”.

Some rules follow:

  • Losing state means Terraform believes nothing exists and plans to create everything again, as duplicates.
  • State can hold secrets. A database password generated by Terraform is stored in it in plain text. Treat the file like a credential.
  • Never edit it by hand. Use terraform state list and state show to read it. To rename a resource in code without destroying it, add a moved block. To adopt something created by hand, use an import block. To stop managing something without deleting it, use a removed block.
  • Never keep it in Git or only on a laptop. Two people applying from two copies of state will undo each other’s work. A shared, locked remote backend fixes that, and it is the subject of the next lesson.

Terraform or OpenTofu?

In August 2023 HashiCorp moved Terraform from an open-source licence to the Business Source License. In response, a group of companies forked the last open version as OpenTofu, which joined the Linux Foundation. The OpenTofu video in deeper says it later moved to the CNCF. The latest releases when I checked were Terraform 1.17.2 and OpenTofu v1.13.10, and their version numbers no longer line up. They read the same HCL, use the same providers and the same state format, and differ in licence, governance, registry and a growing set of features in each direction. OpenTofu, for example, can encrypt state on the client side. Unless your organisation has a licensing reason or needs a feature only one has, the skills transfer completely.

About the video

The embed is Part 3, “Basic Terraform Usage”, from DevOps Directive’s “Complete Terraform Course - From BEGINNER to PRO!” by Sid Palas, published February 2022. It runs from 28:32 to 58:23, the theory and its demo. The full course is 2 hours 38 minutes. The course’s written companion splits Part 3 into init, state, plan/apply/destroy, remote backends and a sample application. It predates OpenTofu and Terraform’s newer import and removed blocks, which is why the state video in deeper is worth the extra 14 minutes. English was judged from the title, description, channel and its English auto-caption track.

Where this fits

One person applying from a laptop works for a demo. Next, how a team shares state, reuses code and runs the same configuration for dev and prod: modules, environments and remote state.

Check yourself

  1. 01Why run plan before apply, and what should you look for?

    plan shows exactly what will be created, changed or destroyed. Look for unexpected destroys, and especially replacements (-/+), which delete a resource and create a new one.

  2. 02You delete terraform.tfstate by accident. What does the next plan want to do?

    Create everything again, because Terraform no longer knows those resources exist. They become unmanaged duplicates unless you import them back into state.

  3. 03Why should state not live in the Git repository with the code?

    It can contain secrets in plain text, and two people applying from different copies would overwrite each other's state. It belongs in a locked, access-controlled remote backend.

  4. 04What is .terraform.lock.hcl for, and should you commit it?

    It records the exact provider versions and checksums that init selected, so every machine uses the same ones. Yes, commit it.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark