3: Core Terraform workflow

    Describe the Terraform workflow (Write -> Plan -> Apply)

    The core workflow is the contract between a practitioner and the Terraform CLI: declarative HCL in version control on one side, mutating infrastructure operations on the other side, and a small set of subcommands that bridge them. The official documentation describes three named stages of the day-to-day loop: Write, Plan, and Apply. Every other subcommand discussed in this chapter exists to support that loop, and every exam scenario about which command to run for a given intent maps to one of those three stages plus the one-time setup performed by init.

    The Write stage is where a practitioner authors or edits .tf files inside a working directory. A working directory is any filesystem directory that contains at least one .tf file. It does not need to be a git repository, although it almost always is in practice. The HCL the author writes during this stage is purely declarative: it describes the desired end state, not the order of API calls. Terraform Core computes a dependency graph from the references between resources at plan time, so the order in which blocks appear in the file does not affect execution order. During this stage the practitioner makes use of terraform fmt to canonicalize whitespace and terraform validate to catch syntax and internal-consistency errors before they reach a remote API, but neither of those subcommands mutates anything and neither contacts a provider.

    The Plan stage takes the current working directory configuration plus the current state and computes a set of proposed changes. The subcommand for this stage is terraform plan. By default plan performs a refresh against the remote APIs to detect drift, then renders the diff between what the state file says exists and what the configuration says should exist. The diff is reported as a list of + (create), - (destroy), ~ (update in place), and +/- (destroy then create) actions, plus the count of each. Reading a plan carefully is the single most important defensive habit during the workflow loop: every destructive symbol means a real resource is about to be deleted or replaced.

    The Apply stage takes a plan (either implicitly recomputed by terraform apply, or explicitly saved to a file by terraform plan -out=tfplan and then consumed by terraform apply tfplan) and executes the create, read, update, and delete API calls against each provider. The apply walks the dependency graph in topological order, parallelizing operations on independent resources up to the value of -parallelism (default 10). After each successful operation the state file is updated, so even if the apply is interrupted partway through, the state reflects the operations that already completed. This is why Terraform can be safely retried after a network blip: the next plan will see only the operations that did not complete.

    The workflow is a loop, not a one-shot pipeline. The expected day-to-day rhythm is to edit a small piece of configuration, run plan to confirm the diff matches the intent, run apply to execute it, then return to editing. Large refactors are split into multiple commit-sized iterations so each plan stays small enough to read end to end. A common anti-pattern in teams adopting Terraform is the multi-day stale branch that accumulates dozens of resource changes; when the long-lived branch finally lands, the plan output is too large to audit, and a destructive symbol that would have been obvious in a small diff hides inside hundreds of lines of context.

    init sits outside the Write/Plan/Apply loop but is a prerequisite to it. It is the only subcommand that needs to run before any of the others, and it is the only subcommand that downloads providers and modules or configures the backend. Re-run init whenever required_providers changes, whenever a module source or version changes, or whenever the backend configuration changes. A clean working directory on a fresh checkout always starts with init.

    Where each stage produces or consumes artifacts

    project-root/
    |-- main.tf written/edited during Write stage
    |-- variables.tf written/edited during Write stage
    |-- outputs.tf written/edited during Write stage
    |-- terraform.tfvars optional input values
    |-- .terraform/ created by init: provider binaries, module cache
    |-- .terraform.lock.hcl created/updated by init: provider version pins
    |-- terraform.tfstate created/updated by apply (local backend only)
    |-- terraform.tfstate.backup previous state, kept after every apply
    `-- tfplan optional, created by plan -out=, consumed by apply
    

    The artifacts above split cleanly into source-controlled files (everything not under .terraform/ and not a state file) and machine-managed files (.terraform/, .terraform.lock.hcl, state and plan files). The lock file is a special case: it is machine-generated but must be committed to version control, because it pins the exact provider versions that every collaborator and every CI job will install during their init.

    A worked end-to-end pass through the workflow

    The fictional file below contains a single resource, a random pet name. The provider is hashicorp/random, which has no real backend dependency, so the example runs deterministically on any machine.

    terraform {
     required_version = ">= 1.12.0"
     required_providers {
     random = {
     source = "hashicorp/random"
     version = "~> 3.6"
     }
     }
    }
    
    resource "random_pet" "service" {
     length = 2
     separator = "-"
    }
    
    output "service_name" {
     value = random_pet.service.id
    }
    

    A first pass through the workflow on this file looks like this:

    # Write stage: file authored above, formatted with fmt
    terraform fmt
    
    # One-time setup: download the random provider, write the lock file
    terraform init
    
    # Offline check that the HCL parses and references resolve
    terraform validate
    
    # Plan stage: compute the diff. Output ends with "1 to add, 0 to change, 0 to destroy."
    terraform plan -out=tfplan
    
    # Apply stage: execute the saved plan. State is created or updated on success.
    terraform apply tfplan
    
    # Inspect the output
    terraform output service_name
    

    💡 Exam Trap: Questions often ask which subcommand is run "first" on a new working directory. The answer is always terraform init, not plan and not validate. Both plan and validate need the .terraform directory that init populates to load provider schemas; running them on an uninitialized directory returns an error telling the practitioner to run init first.

    💡 Exam Trap: The workflow is described in the official documentation as Write -> Plan -> Apply, with init as a one-time setup step that re-runs only when providers, modules, or backends change. Distractor options sometimes list validate or fmt as one of the three named stages of the loop; they are part of the Write stage's hygiene checks, not separately named stages.

    ⚠️ Anti-Pattern: Treating the workflow as Write -> Apply by skipping plan. Running terraform apply without a saved plan triggers an implicit plan first and prompts for approval, which feels equivalent. The risk is that CI systems and team members never see the proposed diff before approval; nothing forces a human reviewer between intent and mutation. Saving plans with -out and reviewing them in code review or in a CI artifact restores the gate.

    🎯 Scenario: An engineer pulls a colleague's branch, edits one resource, and runs terraform plan. The CLI errors out with a message about an unconfigured backend. The fix is to run terraform init first: the colleague's branch added a new module whose provider was not yet downloaded into the practitioner's .terraform/ directory, and any subcommand that needs provider schemas fails until init repopulates the cache and reconciles the lock file.

    Decision Anchor: Choose terraform plan -out=tfplan followed by terraform apply tfplan when running in CI, when destructive changes are expected, or when a human must approve the diff between proposing and executing. Choose plain terraform apply when iterating locally on safe resources where re-running plan is acceptable and the prompt for approval is sufficient.

    Mapping intents to subcommands

    The diagram captures one full lap of the loop. The branch back from "Plan output matches intent? No" to the Write stage is where most defects are caught: a destructive symbol in the plan signals that the configuration says something the author did not intend. The branch from "I" back to "Edit HCL" reflects the steady-state reality that infrastructure code is never finished; the loop continues for the lifetime of the project.

    The Write -> Plan -> Apply naming is sometimes paraphrased in third-party material as Author -> Preview -> Execute or Edit -> Diff -> Deploy. Those paraphrases describe the same loop but are not the names used in the official Terraform documentation. The exam uses the documented names, and distractor options sometimes flip the order or insert an extra "Test" or "Validate" stage into the named loop. Memorize the canonical three: Write, Plan, Apply.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the HashiCorp - Terraform Associate learning hub.