Lesson 03 beginner

The Terraform Core Workflow

Run init, fmt, validate, plan, apply and destroy on a real Docker setup, read a plan symbol by symbol, save plans to files and use refresh-only, replace and the new minimal refresh mode.

Every Terraform project, from a laptop experiment to a bank’s production platform, uses the same short loop: init, plan, apply, with fmt and validate as cheap checks along the way and destroy at the end of a resource’s life. In this lesson you run the whole loop against Docker on your machine and learn to read a plan the way reviewers do.

The project

Create a folder called orbit-local with this main.tf. Make sure Docker is running first (docker ps should work).

terraform {
  required_version = ">= 1.17.0"

  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 4.0"
    }
  }
}

provider "docker" {}

resource "docker_network" "orbit" {
  name = "orbit"
}

resource "docker_image" "web" {
  name         = "nginx:1.27-alpine"
  keep_locally = true
}

resource "docker_container" "web" {
  name  = "orbit-web"
  image = docker_image.web.image_id

  networks_advanced {
    name = docker_network.orbit.name
  }

  ports {
    internal = 80
    external = 8080
  }
}

keep_locally = true tells the provider not to delete the image from your machine on destroy, which saves a download next time.

Docker Desktop on Windows? If the provider cannot connect, set the host explicitly: provider "docker" { host = "npipe:////.//pipe//docker_engine" }. On Linux and macOS the default socket works.

Step 1: init

terraform init prepares the folder. It downloads the providers named in required_providers, any modules, and connects to the state backend.

$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding kreuzwerker/docker versions matching "~> 4.0"...
- Installing kreuzwerker/docker v4.6.0...
Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above.
Terraform has been successfully initialized!

Run init again whenever you add a provider or module, change the backend, or clone the repository fresh. It is safe to run any time. terraform init -upgrade moves providers to the newest version your constraints allow and rewrites the lock file.

Step 2: fmt and validate

Two fast checks that need no API access:

$ terraform fmt -recursive
main.tf
$ terraform validate
Success! The configuration is valid.

fmt rewrites files to the standard layout (it printed main.tf because it fixed alignment there). validate checks syntax, references and argument types: a typo like docker_imag.web fails here, in a second, instead of halfway through an apply. Since 1.15, validate also checks the backend block.

Step 3: plan and how to read it

$ terraform plan
Terraform will perform the following actions:

  # docker_container.web will be created
  + resource "docker_container" "web" {
      + id    = (known after apply)
      + image = (known after apply)
      + name  = "orbit-web"
      + ports {
          + external = 8080
          + internal = 80
          + ip       = "0.0.0.0"
          + protocol = "tcp"
        }
    }

  # docker_image.web will be created
  + resource "docker_image" "web" { ... }

  # docker_network.orbit will be created
  + resource "docker_network" "orbit" { ... }

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

The symbols are the whole language of plans:

SymbolMeaningHow worried to be
+CreateNormal
~Update in placeRead which attribute changes
-/+Destroy, then create a replacementStop and read: data or IP addresses may be lost
+/-Create replacement first, then destroy (create_before_destroy)Safer replacement, still read it
-DestroyMake sure this is what you meant
<=Read a data sourceNormal

(known after apply) means the value only exists once the resource is created, like an ID assigned by the API. When a replacement happens, the plan marks the culprit with # forces replacement next to the attribute that caused it.

Step 4: apply

$ terraform apply
...
Plan: 3 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Enter a value: yes

docker_network.orbit: Creating...
docker_image.web: Creating...
docker_network.orbit: Creation complete after 2s
docker_image.web: Creation complete after 6s
docker_container.web: Creating...
docker_container.web: Creation complete after 1s

Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
$ curl -s localhost:8080 | grep title
<title>Welcome to nginx!</title>

Notice the order: the network and image were created in parallel, and the container waited for both because it references them.

Now change the external port to 8081 and plan again. The container shows -/+ with # forces replacement on the port, because Docker cannot change a published port on a running container. That is exactly the kind of line a reviewer should notice.

Saved plans: approve exactly what you reviewed

Between your plan and your apply, someone else could change the infrastructure or merge new code. A saved plan guarantees that apply does exactly what you reviewed:

$ terraform plan -out=orbit.tfplan
Saved the plan to: orbit.tfplan
$ terraform show orbit.tfplan
$ terraform apply orbit.tfplan

Applying a saved plan does not ask for confirmation, because the review already happened. If the state changed since the plan was made, Terraform refuses to apply a stale plan. This is the pattern CI pipelines use (lesson 14). Plan files can contain sensitive values, so treat them like secrets and do not commit them.

Handling drift

Change something behind Terraform’s back:

$ docker rm -f orbit-web
orbit-web
$ terraform plan
  # docker_container.web will be created
  + resource "docker_container" "web" {
...
Plan: 1 to add, 0 to change, 0 to destroy.

During refresh, Terraform found that the container in its state no longer exists and planned to create it again. That difference between code and reality is called drift. You have three tools for it:

  • terraform apply puts reality back to what the code says. Usually what you want.
  • terraform plan -refresh-only shows what changed outside Terraform without proposing fixes, and terraform apply -refresh-only accepts reality into the state. Use it when the outside change was intentional and you will update the code next.
  • terraform apply -replace="docker_container.web" forces one resource to be destroyed and recreated even though its code did not change, for example when a container or VM is in a bad state. It replaced the old terraform taint command.

Faster plans on big projects

Before planning, Terraform refreshes every resource in state by calling the provider APIs. On a project with thousands of resources that can take minutes. Terraform 1.17 adds -minimal-refresh, which only refreshes resources that have proposed changes:

$ terraform plan -minimal-refresh

The trade-off: drift on resources you did not touch goes unnoticed in that plan, so keep a regular full plan (a nightly drift check, lesson 14). -refresh=false skips refreshing completely and is only for emergencies.

Seeing the dependency graph

terraform graph prints the dependency graph. Since 1.16 it can output Mermaid, which GitHub and most wikis render as a diagram:

$ terraform graph -format=mermaid > graph.md

Step 5: destroy

$ terraform destroy
Plan: 0 to add, 0 to change, 3 to destroy.
  Enter a value: yes
Destroy complete! Resources: 3 destroyed.

destroy is a plan in reverse order: the container goes first, then the network and the image. To remove only one resource for good, delete it from the code and apply; that leaves a reviewable history in Git. terraform destroy -target=... exists, but targeting is for emergencies, not routine work.

Quick reference

TaskCommand
Prepare a folderterraform init
Upgrade providers within constraintsterraform init -upgrade
Format every fileterraform fmt -recursive
Check formatting in CIterraform fmt -check -recursive
Validate the configurationterraform validate
Preview and save a planterraform plan -out=orbit.tfplan
Apply a saved planterraform apply orbit.tfplan
Accept outside changes into stateterraform apply -refresh-only
Force one resource to be recreatedterraform apply -replace="docker_container.web"
Refresh only what changes (1.17)terraform plan -minimal-refresh
Dependency graph as Mermaid (1.16)terraform graph -format=mermaid
Remove everythingterraform destroy

Exercise

A plan shows -/+ next to a database, with # forces replacement on the storage_type attribute. What does that mean?

  1. The database will be updated without downtime
  2. Terraform will create a second database and keep both
  3. The database will be destroyed and a new one created, which can lose data unless you plan for it
  4. The change will be skipped because it is unsafe
Show answer

Answer: C. -/+ means destroy then create. The comment tells you which attribute the provider cannot change in place. For stateful resources, stop and look for a safer path (a supported in-place change, a migration, or create_before_destroy).

Exercise

A teammate scaled a container’s memory by hand during an incident and wants Terraform to accept that value for now. Which command records reality in state without changing infrastructure?

  1. terraform apply -replace
  2. terraform apply -refresh-only
  3. terraform plan -minimal-refresh
  4. terraform init -upgrade
Show answer

Answer: B. -refresh-only updates the state to match the real world and changes nothing else. Then update the code to the new value, or the next normal plan will revert it.

Key takeaways

  • The loop is init, plan, apply; fmt and validate are free checks you run every time.
  • Read every plan. -/+ and - deserve a second look, especially on anything holding data.
  • Saved plans (plan -out, then apply the file) guarantee you apply what you reviewed.
  • Drift: apply fixes reality, -refresh-only accepts it, -replace rebuilds one resource.
  • -minimal-refresh (1.17) speeds up big plans; keep a full drift check elsewhere.
  • Remove resources by deleting code and applying, not with -target.

FAQ

Is terraform plan safe to run against production?

Yes. Plan only reads: it calls read APIs and never changes infrastructure. It does take the state lock while it runs, so a plan can briefly block someone else’s apply.

What is the difference between terraform apply and apply with a saved plan?

Plain apply creates a fresh plan and asks you to confirm it. Applying a saved plan file runs exactly the reviewed actions, with no prompt, and fails if anything changed since the plan was made.

Why does plan show changes I did not make?

Either the infrastructure drifted (someone changed it outside Terraform), a provider upgrade changed how an attribute is read, or your code has a value that the API normalises differently (for example, a JSON policy with different spacing). Read the attributes marked with ~ to see which.

Where did terraform taint go?

It is deprecated. Use terraform apply -replace="<address>", which shows the replacement in a plan before doing it instead of silently marking the resource.

Can I cancel an apply halfway?

Press Ctrl+C once: Terraform finishes the in-flight API calls, saves state and stops. Pressing it twice kills it immediately and can leave state out of date, so avoid that.

↑ ↓ navigate Enter open Esc close