Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 37 ยท Infrastructure as Code Basics

The Core Terraform Workflow: Write, Plan, Apply

Understand the Terraform workflow in depth: init, fmt, validate, plan, saved plans, apply, destroy, -target, -replace, refresh-only and exit codes, with a plan diff stand-in.

Every Terraform project, from a one-file experiment to a hundred-module platform, follows the same loop: write configuration, plan to preview, apply to execute. The previous lesson ran these commands once. Here you learn what each really does, which options matter in daily work, and how to read a plan like a professional, because the plan is where mistakes are caught.

flowchart LR
    W["Write<br/>.tf files"] --> F["fmt + validate"]
    F --> I["init"]
    I --> P["plan"]
    P --> R{"Looks right?"}
    R -- no --> W
    R -- yes --> A["apply"]
    A --> W
    A --> D["destroy<br/>(when finished)"]

The loop: edit, check, plan, review, apply. Destroy ends the life of an environment.

Write, format, validate

While you write, two commands give instant feedback without touching any cloud:

Terminal
terraform fmt -recursive
terraform validate

fmt normalizes whitespace and alignment so diffs show only real changes. validate loads the configuration and checks that blocks are well-formed, that references point at things that exist, and that argument types make sense. It needs init first (providers supply the schemas) but never contacts a real API, so it is safe in pre-commit hooks and CI.

init: when to run it again

terraform init is idempotent. Run it when you clone a repository, add or change a provider, change a module source, or change the backend (where state is stored). terraform init -upgrade lets Terraform pick the newest provider versions that satisfy your constraints and rewrites the lock file. terraform init -backend=false skips the backend, handy for validation in CI.

plan: reading the diff

A plan answers one question: what must change so reality equals the configuration? It does this in three steps:

  1. Refresh (by default): ask the provider about each tracked object to learn its current real attributes.
  2. Compare desired attributes from configuration with the refreshed ones.
  3. Decide an action for every resource.

The possible actions and their symbols:

Symbol Action Meaning
+ create A new object appears in configuration
~ update in place An attribute changed and the provider can change it live
-/+ replace An attribute that cannot change live was edited; destroy then create
+/- replace (create first) The same, with create_before_destroy
- destroy The block was removed from configuration
<= read A data source is read during the plan

A typical update looks like this:

TEXT
  # aws_instance.web will be updated in-place
  ~ resource "aws_instance" "web" {
        id            = "i-0abc123"
      ~ instance_type = "t3.micro" -> "t3.small"
        # (12 unchanged attributes hidden)
    }

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

(Example output.) Learn to look for three danger signs: any -/+ on a database, any destroy you did not expect, and # forces replacement next to an attribute. When a plan says a resource "must be replaced", find the line marked # forces replacement to see which edit caused it.

Replacing a database, a disk or a load balancer can mean data loss or a new IP address. Stop and read the plan whenever you see -/+ on something stateful.

Seeing it: a plan diff stand-in

The Python stand-in below is not Terraform, but it imitates the decision rule. It compares desired resources with what is recorded in the state, using a list of "immutable" attributes that force replacement.

Python Diffing desired state against actual state (stand-in)

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.

Notice how server.cache is replaced because its image changed, while server.web is only updated because size can change live. Real providers declare this per attribute in their schema.

Saved plans

By default apply makes a fresh plan and asks you to confirm. In teams you often want to approve one exact plan and apply exactly that:

Terminal
terraform plan -out=tfplan
terraform show tfplan          # read it again
terraform apply tfplan         # applies exactly this plan, no prompt

If someone changed the state in between, Terraform refuses a stale plan. Saved plans can contain secrets, so treat the file like state. terraform show -json tfplan prints machine-readable output that policy tools can check in CI.

apply: ordering and failures

During apply Terraform walks the dependency graph (next lessons: how Terraform works and dependencies), running independent resources in parallel (10 at a time by default; change with -parallelism=N). If a resource fails, Terraform stops starting new work, finishes what is running, and saves what succeeded. Fix the cause and run apply again; it continues from the new state. There is no automatic rollback: the environment is simply left half-built until you fix it or destroy it.

Useful flags

Terminal
terraform plan -var="region=eu-west-1"        # set an input variable
terraform plan -var-file=prod.tfvars          # a file of variables
terraform plan -target=aws_instance.web       # only this resource and its dependencies
terraform plan -replace=aws_instance.web      # force replacement of one resource
terraform plan -refresh-only                  # only update state to match reality
terraform plan -destroy                       # preview what destroy would do
terraform plan -detailed-exitcode             # 0 = no changes, 1 = error, 2 = changes
  • -target is for emergencies. It skips parts of the graph and can leave things inconsistent, so Terraform warns every time.
  • -replace replaces the older terraform taint workflow: you pick the resource to rebuild and still see it in the plan.
  • -refresh-only records drift (someone edited a resource in the console) into the state without changing infrastructure.
  • -detailed-exitcode makes CI able to fail a pipeline when drift exists.

destroy and show

terraform destroy is the same as terraform apply -destroy: Terraform plans deletion of everything in state, in reverse dependency order, so a subnet is removed after the servers that use it. Combine it with -target rarely. terraform state list (covered in the State chapter) shows what Terraform manages; terraform show prints the current state.

Habits of a careful operator

  • Run fmt and validate before every commit.
  • Always read the whole plan, not just the summary line.
  • Use saved plans in CI so review and apply refer to the same plan.
  • Never -auto-approve against production from a laptop.
  • After an apply, run plan again; the expected output is "No changes".
Python Exit codes and drift (stand-in)

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the line '# aws_db_instance.main must be replaced' with '-/+' tell you?

    -/+ is replacement. For stateful resources this can lose data, so review the attribute marked forces replacement.
  2. 2. Why use terraform plan -out=tfplan followed by terraform apply tfplan?

    A saved plan fixes the set of actions. Reviewers approve a plan, and apply performs that very plan, refusing it if state has moved on.
  3. 3. Which command records manual changes made in the console into state without changing infrastructure?

    A refresh-only run updates state to match reality (drift) and does not create, update or destroy resources.
  4. 4. What does a CI job learn from terraform plan -detailed-exitcode returning 2?

    0 means no changes, 1 means error, 2 means the plan contains changes.

Summary

  • The loop is write, fmt/validate, init, plan, review, apply; destroy ends an environment.
  • A plan refreshes, compares and decides; symbols are +, ~, -/+, -.
  • Treat -/+ on stateful resources and forces replacement lines as red flags.
  • Saved plans (-out) make review and apply identical.
  • -target and -replace are surgical tools; -refresh-only records drift; -detailed-exitcode fits CI.
  • Terraform does not roll back a failed apply: fix and apply again.

Next: How Terraform Works: Core, Providers and State