Lesson 2 of 7 in Infrastructure as Code with Terraform and OpenTofu

The workflow: init, plan, apply, destroy

Core12 min

Every Terraform/OpenTofu run follows the same loop: init downloads the plugins, plan shows what would change, apply makes the change, and destroy removes what the configuration created. The plan is a preview you read before anything happens.

Draft. This lesson is written and waiting for a person to run every command and review it. It is safe to learn from, but check the official documentation for anything you depend on.

Read these first: What Infrastructure as Code means

The problem this solves

Changing real infrastructure is risky because a small edit can delete something important. You need a way to see the effect of an edit before it happens.

The plan step gives you that. The tool compares your files with what it recorded earlier and with what exists now, then prints exactly what it would create, change or remove. Nothing changes until you approve.

How it works

The parts involved in one run
The parts involved in one runThe command line reads your config files, uses a provider plugin to talk to the real target, and records the result in a state file.readscallscreates orchangesrecordsConfig filesmain.tfterraform / tofuthe command lineProvider pluginlocal, random, aws...Real targeta file, a server...Statewhat was created
  • Control
  • Runs code
  • Other
  • Data

The command line reads your config files, uses a provider plugin to talk to the real target, and records the result in a state file.

  1. Config files to terraform / tofu: reads
  2. terraform / tofu to Provider plugin: calls
  3. Provider plugin to Real target: creates or changes
  4. terraform / tofu to State: records
The workflow in order
The workflow in orderYou write config, init downloads providers, plan previews the change, apply makes it and the result is saved to state.1 downloadplugins2 compare3 youapprove4 save resultWriteedit main.tfinitget providersplanpreview the diffapplymake the changeStatesaved afterwards
  • People and clients
  • Control
  • Runs code
  • Data

You write config, init downloads providers, plan previews the change, apply makes it and the result is saved to state.

  1. Write to init: 1 download plugins
  2. init to plan: 2 compare
  3. plan to apply: 3 you approve
  4. apply to State: 4 save result

The configuration is written in HCL (HashiCorp Configuration Language), a small language for blocks and arguments. A resource block says one thing should exist, for example a file. Its type, such as local_file, tells the tool which provider handles it.

init looks at which providers your files need and downloads them into a hidden .terraform folder. It also writes .terraform.lock.hcl, which pins the exact provider versions so teammates get the same ones. You commit that lock file.

plan builds a list of actions. In its output a + means create, - means destroy, ~ means change in place, and -/+ means destroy and create again, which the plan marks with the words forces replacement. Read the final summary line first, then read any - lines carefully.

apply runs the plan after you type yes, and destroy is a plan that removes everything the configuration manages.

Try it yourself

This uses the free local and random providers. They create a text file and a random name on your laptop. Init needs internet access to download the providers, nothing else.

  1. 1
    Write a configuration
    mkdir -p ~/iac-lab/workflow && cd ~/iac-lab/workflow
    cat > main.tf <<"EOF"
    terraform {
      required_providers {
        local  = { source = "hashicorp/local" }
        random = { source = "hashicorp/random" }
      }
    }
    
    resource "random_pet" "name" {
      length = 2
    }
    
    resource "local_file" "greeting" {
      filename = "greeting.txt"
      content  = format("Hello from %s", random_pet.name.id)
    }
    EOF

    Two resources. The file's content refers to the pet name, so Terraform/OpenTofu knows it must create the name first.

  2. 2
    Initialise and validate
    terraform init
    terraform validate

    You should see

    Success! The configuration is valid.

    init prints a message saying it was successfully initialized. With OpenTofu use tofu in place of terraform in every command. Nothing exists yet.

  3. 3
    Preview the change
    terraform plan

    Expect two resources marked with + and a last line of Plan: 2 to add, 0 to change, 0 to destroy. Some values show as (known after apply) because they do not exist yet.

  4. 4
    Apply it
    terraform apply
    cat greeting.txt; echo

    Type yes when asked. The summary should say Apply complete! Resources: 2 added, 0 changed, 0 destroyed. and the file contains Hello from followed by a random two-word name.

  5. 5
    Run plan again with no edits
    terraform plan

    Expect No changes. Your infrastructure matches the configuration. This is idempotence in action.

  6. 6
    Change something, then clean up
    sed -i.bak 's/length = 2/length = 3/' main.tf
    terraform plan
    terraform destroy

    The plan shows the random name being replaced (-/+) and the file updated, because the file depends on the name. Type yes at destroy to remove both. sed -i.bak works on Linux and macOS.

What breaks, and where to look

  • Error: Inconsistent dependency lock file, or Error: Failed to query available provider packages.

    WHY IT HAPPENS
    init was never run in this folder, the provider could not be downloaded (no internet, proxy, firewall), or the provider name in required_providers is misspelled.
    CHECK FIRST
    Run terraform init again and read the first error line. Check the source address, for example hashicorp/local, and your network.
  • The plan says something will be destroyed or replaced that you did not expect.

    WHY IT HAPPENS
    Some arguments cannot be changed on an existing object, so the tool must delete and recreate it. The plan marks this with forces replacement.
    CHECK FIRST
    Search the plan output for forces replacement and must be replaced, find which argument caused it, and decide if recreation is acceptable before you type yes.
  • You applied and later cannot remember what changed.

    WHY IT HAPPENS
    Apply was run without reading or saving the plan, so there is no record of the intended change.
    CHECK FIRST
    Use terraform plan -out=tfplan, review it, then terraform apply tfplan so the apply runs exactly what you reviewed.

When not to use this

  • A plan only knows what the provider reports. It cannot warn you about application-level damage, such as a database losing data when its server is replaced.
  • Applying straight from a laptop is fine for learning. For shared infrastructure, teams usually run plan and apply from a pipeline so everyone follows the same steps.

Check yourself

What does init do and what file does it write that you should commit?

It downloads providers and modules. It writes .terraform.lock.hcl, which pins provider versions and should be committed.

What does -/+ in a plan mean?

The object will be destroyed and created again, which the plan flags as forces replacement.

Why is a second plan with no edits a useful check?

It should report no changes. If it does not, something differs between the files, the state and the real target.

Lesson 64 of 92 in the DevOps path

Search

Search cheat sheets and projects