Terraform Workflow: Init, Plan, Apply and Destroy
Introduction
This Terraform workflow lesson covers the Core Terraform workflow area of the Terraform Associate (004) exam, objectives 3a to 3g. HashiCorp lists seven objectives here but does not publish a question weighting for this area. The exam lasts one hour, tests Terraform 1.12, and mixes true/false, multiple-choice and multiple-answer questions.
Every Terraform user, from a student to a platform team, repeats the same loop: write configuration, preview the change, apply it, and eventually destroy it. The commands are few, but the exam asks precise questions about what each one reads, writes and changes. Knowing the side effects of init, plan, apply and destroy helps you choose the right operation for each scenario.
After this lesson you will be able to describe the write, plan, apply workflow, run init, validate, plan, apply, destroy and fmt with their common options, save and apply a plan file, and pick the right command for a given situation.
Learning objectives
- Describe the three stages of the core workflow: write, plan, apply.
- Explain everything
terraform initdoes and when it must be run again. - Distinguish
terraform validatefromterraform planand say what each can and cannot detect. - Read a plan, interpret the symbols
+,-,~,-/+, and save a plan with-out. - Use
terraform applywith and without a saved plan, and understand-auto-approve. - Use
terraform destroyand-targetwith appropriate caution. - Format code with
terraform fmtand know its main flags.
3a. The write, plan, apply workflow
HashiCorp describes the core workflow in three steps:
- Write infrastructure as code in
.tffiles, usually in version control. - Plan: Terraform compares your configuration with the state and the real infrastructure, and shows what it would do.
- Apply: Terraform performs the planned actions in dependency order and updates the state.
Around these three steps sit supporting commands: init before anything else, validate and fmt while writing, and destroy when the infrastructure is no longer needed.
A working directory that holds .tf files is called a root module. Terraform combines the ordinary .tf and .tf.json files in that directory into one configuration; file or block order does not determine resource execution order. Names such as main.tf, variables.tf and outputs.tf are conventions. Special override files have separate merge rules.
Example. A small team at a retail company keeps a Terraform configuration in Git. Priya edits main.tf to add a second subnet (write), opens a pull request where the pipeline runs terraform plan -out=tfplan and posts a summary for review (plan), and after approval the pipeline applies the reviewed saved plan (apply). If merging requires a fresh plan, that final plan must also be reviewed. Reviewers can inspect an access-controlled plan summary without provider credentials; avoid exposing secrets in pull-request logs or artifacts.
3b. terraform init
terraform init prepares a working directory. It is the first command you run after writing a new configuration or cloning an existing one, and it is safe to run repeatedly (it is idempotent). It performs these tasks:
| Task | Details |
|---|---|
| Backend initialisation | Configures the backend from the backend block (or cloud block) so state can be stored and locked |
| Child module installation | Downloads modules referenced in module blocks into .terraform/modules |
| Provider installation | Downloads the providers required by the configuration into .terraform/providers and writes or checks .terraform.lock.hcl |
Common options:
| Option | Effect |
|---|---|
-upgrade |
Disregards locked provider version selections and selects newer allowed versions; also updates installed modules according to their sources and constraints |
-migrate-state |
Moves existing state to a newly configured backend |
-reconfigure |
Reconfigures the backend and ignores any saved configuration, without migrating state |
-backend=false |
Skips backend initialisation (useful for validate in CI) |
-backend-config=... |
Supplies partial backend configuration such as a key or file |
Run init again when you add or change a provider, a module source or version, or the backend configuration. Terraform will tell you with an error such as "Module not installed" or "Backend initialization required".
init installs dependencies and configures state storage rather than provisioning resources or refreshing managed resource objects. It can need credentials for remote backends, private registries or private module sources. These are different from the credentials providers use later to manage infrastructure.
Exam tip. If a question says "a colleague cloned the repository and terraform plan fails with a missing provider", the answer is terraform init.
3c. terraform validate
terraform validate checks whether the configuration is syntactically valid and internally consistent. It examines the configuration without accessing remote services or state: it verifies HCL syntax, that referenced variables and resources exist, that attribute names belong to the resource schema, and that value types are right.
Requirements and limits:
- The directory must be initialised (providers are needed to know the schemas), but you can run
terraform init -backend=falsefirst. - It does not need cloud credentials.
- It does not detect problems that only appear against real infrastructure: a bucket name already taken, an AMI that does not exist, a quota that is exceeded or insufficient permissions. Only
planorapplyfind those. terraform validate -jsonproduces machine-readable output for CI pipelines.
Example. The pipeline of a bank runs terraform fmt -check, terraform init -backend=false and terraform validate on every commit because these steps catch configuration errors before a plan. Validation does not require resource API access, although dependency installation can require private-registry or module-source authentication.
3d. terraform plan
terraform plan creates an execution plan. By default it performs three actions:
- It reads the current state of remote objects already tracked by Terraform (a refresh) so that state matches reality.
- It compares the configuration with that updated state.
- It proposes the set of changes needed to make real infrastructure match the configuration.
The plan does not change infrastructure. It can, however, update the state file in memory for the refresh and it takes a state lock on backends that support locking.
Reading plan output
| Symbol | Meaning |
|---|---|
+ |
Resource will be created |
- |
Resource will be destroyed |
~ |
Resource will be updated in place |
-/+ |
Replacement: destroy the old object, then create its replacement |
+/- |
Replacement: create the replacement before destroying the old object |
<= |
Data source will be read |
The summary line at the end reads, for example, Plan: 2 to add, 1 to change, 1 to destroy. Attributes whose values are not known until apply are shown as (known after apply).
A replacement happens when you change an argument that cannot be updated in place (for example the AMI of an instance on some platforms). The plan marks such an attribute with # forces replacement. This is the line to watch for during reviews, because replacing a database can lose data unless backups, retention and the replacement design preserve it.
Useful options
| Option | Effect |
|---|---|
-out=FILE |
Saves the plan to a file for a later apply |
-var 'name=value' / -var-file=FILE |
Sets input variables |
-target=ADDRESS |
Limits planning to a resource and its dependencies (exceptional use) |
-replace=ADDRESS |
Forces replacement of one resource (replaces the old terraform taint) |
-refresh-only |
Proposes state and root-output updates to match remote objects; apply is needed to persist them |
-refresh=false |
Skips the refresh step |
-destroy |
Plans destruction of the managed objects in the selected state |
-detailed-exitcode |
Exit code 0 means no changes, 1 error, 2 changes present |
-lock=false |
Does not take a state lock (risky) |
-parallelism=N |
Limits concurrent operations (default 10) |
Saved plans
A plan saved with -out is a binary file that records the exact actions and the configuration and state it was based on. Three rules follow:
terraform apply planfileexecutes the recorded plan without generating a new plan or asking for approval. Passing the file is treated as approval; Terraform cannot know whether a human actually reviewed it.- If the current state no longer matches the state snapshot the plan expects, Terraform rejects the stale plan. A console change that has not been recorded in state is different: saved-plan application does not perform a fresh general refresh to discover all intervening drift. Keep the review-to-apply interval short and re-plan after known external changes.
- A plan file may contain sensitive values in clear form, so protect it as you would state. Use
terraform show planfile(or-json) to read it.
For provider installation and lock-file behaviour, revisit Terraform providers, aliases and lock files.
3e. terraform apply
terraform apply executes changes. Without a plan file it first creates and displays a new plan; in interactive mode, when changes are proposed, it asks you to type yes unless approval is bypassed. With a saved plan it executes immediately without asking.
During apply, Terraform builds a dependency graph and processes independent resources in parallel (10 at a time by default), waiting for dependencies. At the end it writes the new state and prints the outputs. If an operation fails midway, resources that were already created remain in state, and nothing is rolled back; fix the problem and run apply again, which continues from the real current situation.
Useful options:
| Option | Effect |
|---|---|
-auto-approve |
Skips approval of the newly generated plan; it does not bind execution to an earlier separately reviewed plan |
-var, -var-file |
Sets variables |
-target, -replace |
As for plan |
-refresh-only |
Applies only the state update after you approve it |
-parallelism=N |
Changes concurrency |
Worked example: choosing the safe pipeline
Scenario. A company deploys to production through a pipeline. The security team wants a human to review exactly what will change and wants the deployment to apply exactly the reviewed change, even if a colleague pushes another commit minutes later. Which pipeline design is best?
Reasoning, step by step.
- The reviewed artefact must be the thing that is applied. A plan generated twice can differ, because the infrastructure or the configuration may change between runs.
- Terraform provides this through a saved plan:
terraform plan -out=tfplan. - The pipeline stores
tfplanas an artefact, showsterraform show tfplanto the reviewer, and after approval runsterraform apply tfplan. No-auto-approveis necessary because supplying the saved plan counts as approval. An incompatible intervening state change causes rejection; unrecorded external drift is not guaranteed to be detected. - The plan file may contain secrets, so the artefact store must be access-controlled.
Solution. plan -out, review, then apply of the saved file.
Why other choices are weaker. Running terraform apply -auto-approve straight after merge applies a new plan nobody reviewed. Running plan for the review and then a separate apply that generates a second plan can apply something different from what was approved. Manually editing state to match the plan is never an acceptable deployment method.
3f. terraform destroy
terraform destroy destroys all the resources managed by the current configuration and state. It is equivalent to terraform apply -destroy: Terraform makes a destroy plan, asks for confirmation, then deletes resources in reverse dependency order, so that, for example, an instance is removed before the subnet that contains it.
Key points:
- It only destroys what is in the state of the working directory. It does not enumerate an entire account to delete untracked objects. Provider-side cascading deletion or shared dependencies can still affect other systems, so inspect the destroy plan and platform behaviour.
terraform plan -destroypreviews the destruction without doing it.-target=ADDRESSselects only part of the graph; inspect the actualterraform plan -destroy -target=ADDRESSresult rather than assuming it deletes exactly one object. Use targeting only for exceptional recovery, then run a full plan.- A
lifecycle { prevent_destroy = true }setting makes Terraform refuse any plan that would destroy that resource. Note that removing the resource block itself also removes the protection with it. - Destroying is the cleanest way to stop paying for a temporary environment such as a test or training lab.
Example. A development team creates a full test environment for each feature branch with a workspace and a variable file. When the branch is merged, the pipeline runs terraform destroy -auto-approve -var-file=feature.tfvars, which requests deletion of managed objects in dependency order. Provider errors, deletion protection or resources outside that workspace can still require cleanup.
3g. terraform fmt
terraform fmt rewrites configuration files to the canonical HCL style: two-space indentation, aligned equals signs in blocks of arguments, and consistent spacing. It only changes style, never the meaning.
| Option | Effect |
|---|---|
| (none) | Formats .tf and .tfvars files in the current directory only |
-recursive |
Also processes subdirectories |
-check |
Changes nothing, prints names of files that need formatting, exits with a non-zero status when formatting is needed |
-diff |
Shows the differences |
-write=false |
Does not overwrite files |
-list=false |
Does not list the names of changed files |
Teams commonly run terraform fmt -check -recursive in CI and an editor plugin or pre-commit hook locally, so that diffs in code review contain real changes only.
Command comparison
| Command | Needs init | Contacts real infrastructure | Changes infrastructure | Changes state |
|---|---|---|---|---|
fmt |
No | No | No | No |
validate |
Yes | No | No | No |
plan |
Yes | Yes (refresh) | No | No (the saved state is not written by a normal plan) |
apply |
Yes | Yes | Yes | Yes |
destroy |
Yes | Yes | Yes (deletes) | Yes |
Common pitfalls and exam tips
- Pitfall: believing that
terraform initprovisions resources. It installs dependencies and sets up the backend; private sources and remote state can require authentication. - Pitfall: assuming
validateproves a plan will succeed. It only checks the configuration offline. - Pitfall: assuming that any external infrastructure change makes a saved plan visibly stale. State consistency checks do not guarantee fresh drift detection; create and review a new plan after a known external change.
- Pitfall: using
-targetas a normal workflow. HashiCorp documents it as an exceptional tool for recovery; routine use leaves the state out of step with the configuration. - Pitfall: forgetting that
-auto-approveskips approval of a newly generated plan. Use an approved saved plan when execution must match a specific review artifact. - Exam tip: a question that describes "check formatting in CI without changing files" points to
terraform fmt -check. - Exam tip: "preview what would be destroyed" is
terraform plan -destroy; "force one resource to be recreated" isterraform apply -replace=ADDRESS. - Exam tip:
terraform init -upgradeis the usual deliberate way to reconsider provider versions within constraints and update the lock file. - Exam tip: study the documented Terraform 1.12 behaviour for exam 004. Newer CLI features are not needed to explain these workflow objectives.
For backend selection and state recovery, continue with Terraform state management and backends.
Mini case study
Situation. Marta joins a team that manages a staging environment. She clones the repository, creates a variable file, and runs terraform plan. She gets "Error: Required plugins are not installed". She then runs terraform init, then terraform plan, which shows Plan: 14 to add, 0 to change, 0 to destroy. She is surprised, because the staging environment already exists. A colleague explains that the state is stored in a remote backend and that Marta's backend block uses a different key by mistake.
Questions.
- Why did the first plan fail and what fixed it?
- Why does the plan want to add 14 resources?
- What should Marta do before running
apply?
Solution.
- The configuration required provider packages that were not installed in her working directory;
terraform initinstalled the locked versions and the plan could run. - With the wrong backend key Terraform reads an empty state, so it believes nothing exists and plans to create everything. Applying would try to create duplicates (or fail on name conflicts).
- She must stop, fix the backend key, run
terraform init -reconfigureto select the correct existing backend state, and check that the new plan shows no unexpected changes. Do not migrate the accidental empty or duplicate state over the real staging state. If anything was applied under the wrong key, inspect both states and the real objects with the team before deciding how to reconcile them.
Key terms
- Root module: the directory in which you run Terraform commands.
- Execution plan: the list of actions Terraform proposes.
- Saved plan: a binary file created with
plan -out. - Refresh: reading real infrastructure to update state.
- Replacement: destroy and create (
-/+). - Canonical format: the style imposed by
terraform fmt.
Summary checklist
- I can state the three stages: write, plan, apply.
- I know
initsets up backend, modules and providers, and can be re-run safely. - I know
validateis offline and needs no credentials. - I can read
+,-,~,-/+in a plan. - I can save a plan with
-outand apply it later. - I know an interactive apply with changes asks for
yesunless given a plan file or-auto-approve. - I know
destroyequalsapply -destroyand works in reverse dependency order. - I can name
fmt -checkandfmt -recursive.
Official sources
- Terraform CLI documentation: https://developer.hashicorp.com/terraform/cli/commands (opens in a new tab)
- Core workflow: https://developer.hashicorp.com/terraform/intro/core-workflow (opens in a new tab)
- Exam objectives (004): https://developer.hashicorp.com/terraform/tutorials/certification-004/associate-review-004 (opens in a new tab)
- Terraform 1.12 plan reference: https://developer.hashicorp.com/terraform/cli/v1.12.x/commands/plan (opens in a new tab)
- Apply reference: https://developer.hashicorp.com/terraform/cli/commands/apply (opens in a new tab)
- Init reference: https://developer.hashicorp.com/terraform/cli/commands/init (opens in a new tab)
- Validate reference: https://developer.hashicorp.com/terraform/cli/commands/validate (opens in a new tab)
- Saved-plan implementation in Terraform 1.12.2: https://raw.githubusercontent.com/hashicorp/terraform/v1.12.2/internal/backend/local/backend_apply.go (opens in a new tab)
