Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Workflows and Collaboration

The Terraform Workflow: init, validate, plan, apply, destroy

Master the everyday Terraform workflow: fmt, validate, plan -out, apply with a saved plan, destroy, variable files, targeted runs and flags that make CI reliable.

Terraform has a small command set, and almost all your work follows one loop: write, format, validate, plan, review, apply. Knowing exactly what each step does, and which flags make the loop safe for teams, separates a comfortable user from a nervous one. This lesson walks through the loop, then adds the habits that matter on a team: saved plans, variable files and careful use of destroy.

The loop

flowchart LR
  W["Write HCL"] --> F["terraform fmt"]
  F --> V["terraform validate"]
  V --> P["terraform plan -out=tfplan"]
  P --> R{"Review OK?"}
  R -->|"No"| W
  R -->|"Yes"| A["terraform apply tfplan"]
  A --> S["State updated"]

Review the plan before every apply; apply the exact plan you reviewed.

init

terraform init prepares a working directory. It configures the backend, downloads providers into .terraform/, downloads modules and creates or checks .terraform.lock.hcl. Run it after cloning, after changing providers, modules or the backend. It is safe to run repeatedly. Useful flags: -upgrade (newer allowed versions), -reconfigure (ignore saved backend settings), -migrate-state (Remote State) and -backend=false (for CI jobs that only validate).

fmt and validate

Terminal
terraform fmt -recursive          # rewrite files to the canonical style
terraform fmt -check -recursive   # exit 3 if anything needs formatting (CI)
terraform validate                # syntax, references, types; no cloud calls

validate needs init first (it needs provider schemas) but talks to no API and needs no credentials, so it is perfect for a quick CI gate.

plan

terraform plan refreshes state, compares it with the code and prints actions. Symbols:

Symbol Meaning
+ create
- destroy
~ update in place
-/+ replace (destroy and create, or the reverse with create_before_destroy)
<= read a data source

Example output (not produced by this site):

TEXT
  # aws_instance.web will be updated in-place
  ~ resource "aws_instance" "web" {
      ~ instance_type = "t3.micro" -> "t3.small"
    }

  # aws_security_group.old must be replaced
-/+ resource "aws_security_group" "old" { ... }

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

A replacement ("forces replacement" appears beside the culprit attribute) deserves the closest look: it can mean downtime or data loss.

Saved plans

Plans are time-sensitive: between your review and your apply, someone may change the infrastructure. Save the plan and apply exactly that file:

Terminal
terraform plan -out=tfplan
terraform show tfplan            # human-readable review
terraform show -json tfplan > plan.json   # for policy tools
terraform apply tfplan           # no prompt, applies precisely this plan

If state changed since the plan was made, Terraform refuses with "Saved plan is stale". Treat the plan file as sensitive: it can contain secret values.

Python Summarize a plan like the CLI does

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.

Variables and var files

Pass input values in layers; later sources override earlier ones:

  1. Defaults in variable blocks
  2. terraform.tfvars and *.auto.tfvars (loaded automatically)
  3. -var-file=prod.tfvars
  4. -var="instance_count=3" and TF_VAR_instance_count=3 (environment)
Terminal
terraform plan -var-file=envs/prod.tfvars -out=tfplan

Keep secrets out of tfvars files that you commit; supply them from the environment or a secret manager.

apply, destroy and targeting

terraform apply without a file builds a fresh plan and asks you to type yes. -auto-approve skips the prompt: acceptable in a pipeline that applies a reviewed saved plan, risky on a laptop. -parallelism=N controls concurrent operations (default 10); lower it when an API rate-limits you.

terraform destroy plans and deletes everything in the state; it is terraform apply -destroy. Use terraform plan -destroy to preview. Pair prevent_destroy (lifecycle rules) with production databases.

-target=ADDRESS restricts a run to one resource and its dependencies. It leaves the rest of the configuration unapplied, so reserve it for recovery. Terraform even prints a warning each time.

Exit codes and automation flags

Terminal
terraform plan -detailed-exitcode   # 0 no changes, 1 error, 2 changes
terraform plan -input=false -lock-timeout=5m -no-color
terraform apply -input=false tfplan

-input=false makes Terraform fail instead of prompting, which is exactly what you want in CI. TF_IN_AUTOMATION=1 tones down the "run terraform apply next" hints.

Python Which command should run?

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.

Habits for teams

  • Run the same Terraform and provider versions everywhere (required_version, lock file).
  • Review the plan, not just the code diff: the plan shows what will really happen.
  • Apply from one place (a pipeline), not from many laptops (Terraform in CI).
  • Never run apply against production without a recent successful plan from the same commit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use terraform plan -out=tfplan followed by terraform apply tfplan?

    A saved plan removes the gap between review and apply.
  2. 2. Which command checks syntax and references without calling any cloud API?

    validate works offline after init, so it needs no credentials.
  3. 3. A plan line with -/+ means:

    -/+ is destroy and create: a replacement.
  4. 4. Which flag stops Terraform from prompting in a pipeline?

    With -input=false, missing input becomes an error instead of a prompt.

Summary

  • The loop is init, fmt, validate, plan, review, apply.
  • Save plans with -out, inspect them with terraform show, and apply the file.
  • Read plan symbols; replacements (-/+) need extra scrutiny.
  • Layer variables with defaults, tfvars files, -var and TF_VAR_*.
  • Use -detailed-exitcode, -input=false and -lock-timeout in automation; keep -target for emergencies.

Next: Workspaces and Multiple Environments