Init, validate, plan, apply and destroy in practice

Beginner · 8 min

What each command in the Terraform loop reads, writes and refuses to do, so a plan you review is the plan that runs, and destroy is never a surprise.

Before thisYour first configuration with local resources

HashiCorp, an IBM Company · 21 min · from 7:46

Init, validate, plan, apply and destroy in practice

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

Taught by HashiCorp, an IBM CompanyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `init` prepares the working directory: it installs providers and modules, configures the backend and writes the lock file. Run it again after changing any of those.
  • `validate` checks syntax and internal consistency only. It never contacts a provider API or reads state.
  • `plan` compares code, state and reality. `plan -out` saves the exact plan, and `apply` on that file applies exactly what was reviewed.
  • `destroy` is `apply -destroy`. `plan -destroy` previews it without changing anything.
  • `plan -detailed-exitcode` returns 0 for no changes, 1 for an error and 2 for changes, which is what scripts and CI check.

One command is not enough

Imagine running a single command called terraform go. It would read your code, install whatever it needs, decide what to change and change it. That sounds convenient until the first time it deletes a database, because the only chance to look at the decision happened after the decision was carried out.

Terraform splits the work into stages, with a pause for a human before the one that does damage. Each stage has a different job and a different failure mode, and knowing which stage you are in is half of debugging.

init: get the directory ready

terraform init does the setup work for a folder. In an empty folder with a .tf file it:

  • installs the providers named in required_providers into .terraform/,
  • installs any modules your code calls,
  • configures the backend, which is where state lives,
  • writes or updates .terraform.lock.hcl, recording the provider versions and checksums it chose.

It is safe to run repeatedly. You run it again whenever you add a provider, change a module’s source or version, or change the backend block. If you are unsure whether to re-run it, run it. OpenTofu’s equivalent is tofu init, and the rest of the commands here work the same way.

validate: is the code well-formed?

terraform validate checks that the configuration is syntactically valid and internally consistent: block names exist, argument types fit, references point at things that exist. The CLI docs say it does not validate remote services such as provider APIs, and that its result does not depend on state. It needs init to have run first, because it checks arguments against the schemas the installed providers declare. In CI you can use terraform init -backend=false before it, so the check needs no credentials.

Because it never reaches the cloud, passing validate proves little about whether apply will work. Think of it as a compiler’s syntax pass. It catches typos in minutes. It will not catch a bucket name someone else already owns.

plan: the decision

terraform plan is the stage that does the thinking. It reads your code, reads state, asks each provider what is really there, and prints the difference. I wrote a small stand-in that does this comparison on made-up data, to show the shape of the output and the counting rule. It is not Terraform, and the resources are invented:

  -   aws_instance.old
  -/+ aws_instance.web
        ami = "ami-0old" -> "ami-0new"
        instance_type = "t3.micro" -> "t3.small"
  +   aws_instance.worker
        ami = "ami-0new"
        instance_type = "t3.small"
        subnet_id = "subnet-a"
      aws_s3_bucket.logs

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

Notice the arithmetic. A replacement (-/+) counts as one add and one destroy. So a plan with one new resource, one deleted and one replaced says “2 to add, 2 to destroy”, and that is the summary line of real Terraform plans too. The next lessons teach you to read the details.

Three flags are worth knowing from the start, as the CLI docs describe them:

  • -out=tfplan saves the plan to a file. The docs call it an opaque format, and tell you to treat it as sensitive because it contains your configuration and variable values.
  • -destroy plans the removal of everything, without doing it.
  • -detailed-exitcode makes the exit status say what happened: 0 means no changes, 1 an error, 2 changes present. A pipeline can use that to fail on drift.

apply: do it

terraform apply with no arguments makes a fresh plan, shows it and asks for the word yes. Reading that prompt is your last review. With a saved plan, terraform apply tfplan skips the question and runs exactly what the file says. That distinction matters in CI. The plan someone approved on Tuesday is the one applied on Wednesday, even if the cloud changed in between. If it changed too much, apply refuses a stale plan instead of improvising.

Terraform walks the dependency graph and runs independent changes in parallel, up to ten at a time by default. After each success it writes state. If an apply is interrupted halfway, state still records what was done, and the next plan picks up from there.

destroy: apply in reverse

The CLI docs say terraform destroy is a shortcut for terraform apply -destroy, and that terraform plan -destroy shows the proposed destruction without carrying it out. Destroy works through the graph backwards, so the server goes before the subnet it lives in. It deletes everything this configuration manages and nothing else, which is the point of state. Use it for temporary environments. Anywhere else, running plan -destroy first and reading it is a good habit.

A loop you can repeat

terraform init
terraform fmt -check
terraform validate
terraform plan -out=tfplan
terraform apply tfplan

Written from the CLI docs, not run here. fmt -check is the formatter’s dry run, covered with linting later. The pattern to build into muscle memory is “init when dependencies change, plan always, apply the plan you read”.

About the video

The embed is HashiCorp’s “Terraform Basics” from September 2024, 21 minutes in full, from “Terraform Workflow - Init” to “Terraform Workflow - Destroy” (7:46 to 15:30). Its chapters cover init, plan, apply, updating resources and destroy. There is no separate validate chapter, so that section above comes from the docs. I did not check which provider its demo uses. It is the vendor’s own tutorial. English was judged from title, channel and an English auto-caption track.

Where this fits

You can run the loop. Next, learn to read the language itself: HCL syntax, blocks, arguments and expressions.

Check yourself

  1. 01You added a new provider to `required_providers` and `plan` fails saying the provider is not installed. What is missing?

    A fresh `terraform init`. Providers, modules and the backend are installed during `init`, so changing any of them means running it again.

  2. 02Your CI job must fail the pipeline when infrastructure has drifted from the code. Which flag helps?

    `terraform plan -detailed-exitcode`. It exits 0 when nothing would change and 2 when something would, so a script can distinguish a clean run from a diff, with 1 meaning an error.

  3. 03Why does the Terraform CLI docs tell you to treat a saved plan file as sensitive?

    A plan file holds the full configuration and the input variable values, including any secrets. It is not safe to leave in a public CI artifact.

  4. 04Does `validate` passing mean `apply` will succeed?

    No. It checks the code against the provider's schema, not against the real API. Quota, naming conflicts, missing permissions and values that only fail at the cloud all appear later.

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