DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 9 of 17
Your progress · 0%
On this page
  1. terraform plan
  2. terraform apply
  3. terraform destroy
  4. When apply goes wrong
↖ Course roadmap
Lesson 9 · Plan, apply, destroy

Plan, apply and destroy

The core loop in depth: what plan compares, saving and applying an exact plan, how drift shows up, forcing a replacement, targeting in emergencies, and destroying safely.

30 min read · beginner · hands-on

By the end of this lesson you'll be able to

0 of 5 complete
Lab status

Verified lab: plan, saved plans, apply, drift, -replace, destroy and the stale-plan error. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: none.
Cloud lab: none; nothing here needs a cloud account.

You've used plan and apply since lesson 1. This lesson goes underneath: what plan actually compares, how to apply exactly what was reviewed, what happens when someone changes things by hand, and the flags you'll reach for when things go wrong.

Plan compares code, state and reality. Apply makes reality match the code, then records it.© Diagram: DevOps Academy

Plan compares code, state and reality. Apply makes reality match the code, then records it.© Diagram: DevOps Academy

terraform plan

A plan answers "what would change?" in three steps:

  1. Refresh. Ask each provider about every resource in state: does it still exist, and what are its current attributes?
  2. Compare the refreshed state with your configuration.
  3. Print the actions needed to make reality match the code.

The lab's first plan, saved to a file:

$ terraform plan -out=tfplan

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # local_file.inventory will be created
  + resource "local_file" "inventory" {
      + content              = (known after apply)
      + directory_permission = "0777"
      + file_permission      = "0777"
      + filename             = "./out/inventory.txt"
      + id                   = (known after apply)
      ...
    }

  # random_pet.server will be created
  + resource "random_pet" "server" {
      + id        = (known after apply)
      + length    = 2
      + separator = "-"
    }

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

─────────────────────────────────────────────────────────────────────────────

Saved the plan to: tfplan

To perform exactly these actions, run the following command to apply:
    terraform apply "tfplan"
terraform plan -out=tfplan
  • terraforminfrastructure as code
  • planpreview changes

(The hash attributes of local_file are trimmed with ....) How to read it:

  • (known after apply): the value doesn't exist yet. The file's content depends on a pet name that hasn't been generated.
  • Defaults show up: file_permission = "0777" wasn't in the code; it's the provider's default, and a bad one: anyone on the machine can read and change the file. Real code sets it explicitly, as lesson 8 does with 0600 and 0700.
  • The summary line is the first thing to check. An unexpected number in "to destroy" is how outages start.

terraform show tfplan prints a saved plan again, for review, and terraform show -json tfplan gives a machine-readable version that policy tools read (lesson 16).

terraform apply

$ terraform apply tfplan
random_pet.server: Creating...
random_pet.server: Creation complete after 0s [id=model-kiwi]
local_file.inventory: Creating...
local_file.inventory: Creation complete after 0s [id=e041d7cb3c1d1c469796feb23dcb0459b375560d]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
$ cat out/inventory.txt
server: model-kiwi
terraform apply tfplan
  • terraforminfrastructure as code
  • applymake the changes
cat out/inventory.txt
  • catprint a file

Applying a saved plan doesn't ask "Are you sure?", because the review already happened, and it does exactly what the plan said. If the state changed since the plan was made, it refuses. A plain terraform apply (no file) makes a fresh plan, shows it, and waits for you to type yes.

A plan run straight after shows nothing to do:

$ terraform plan
random_pet.server: Refreshing state... [id=model-kiwi]
local_file.inventory: Refreshing state... [id=e041d7cb3c1d1c469796feb23dcb0459b375560d]

No changes. Your infrastructure matches the configuration.
terraform plan
  • terraforminfrastructure as code
  • planpreview changes

Drift: when someone changes things by hand

Drift is any change made outside Terraform. In the lab, someone overwrote the managed file:

$ echo "server: hand-edited" > out/inventory.txt
$ terraform plan
random_pet.server: Refreshing state... [id=model-kiwi]
local_file.inventory: Refreshing state... [id=e041d7cb3c1d1c469796feb23dcb0459b375560d]

Terraform will perform the following actions:

  # local_file.inventory will be created
  + resource "local_file" "inventory" {
      + content              = <<-EOT
            server: model-kiwi
        EOT
      ...
    }

Plan: 1 to add, 0 to change, 0 to destroy.
echo "server: hand-edited" > out/inventory.txt
  • echoprint text
  • >write output to a file, replacing it
terraform plan
  • terraforminfrastructure as code
  • planpreview changes

The refresh noticed the file no longer matched what Terraform wrote (the local provider treats a changed file as gone), and the plan puts the code's version back. On AWS, drift looks like a security group rule someone added in the console, which the next apply removes.

When you see drift, decide: was the manual change a mistake (apply, and Terraform repairs it) or the right thing (put it in the code, so the plan shows no changes)? terraform plan -refresh-only shows only the drift, and terraform apply -refresh-only accepts it into state without changing anything real.

Force a replacement

Sometimes you want a fresh object even though nothing changed in the code: a server that's misbehaving, or a key you want rotated.

$ terraform apply -auto-approve -replace=random_pet.server
...
  # local_file.inventory must be replaced
-/+ resource "local_file" "inventory" {
      ~ content              = <<-EOT
            server: model-kiwi
        EOT -> (known after apply) # forces replacement
      ...
    }

  # random_pet.server will be replaced, as requested
-/+ resource "random_pet" "server" {
      ~ id        = "model-kiwi" -> (known after apply)
      ...
    }

Plan: 2 to add, 0 to change, 2 to destroy.
...
random_pet.server: Creation complete after 0s [id=saved-javelin]
...
Apply complete! Resources: 2 added, 0 changed, 2 destroyed.
terraform apply -auto-approve -replace=random_pet.server
  • terraforminfrastructure as code
  • applymake the changes
  • -auto-approveskip the yes prompt

The pet was replaced "as requested", and the file was replaced too, because its content depends on the new name. That's the dependency graph at work. -replace replaced the old terraform taint command.

-target, for emergencies only

-target=local_file.inventory limits a plan to one resource and what it depends on. It's tempting to use every day, but it applies a partial plan, so the rest of the configuration and its state drift apart. Use it to recover from a broken state or an urgent fix, then run a full plan straight after.

terraform destroy

Preview first, then destroy:

$ terraform plan -destroy
...
  # local_file.inventory will be destroyed
  - resource "local_file" "inventory" {
      - content              = <<-EOT
            server: saved-javelin
        EOT -> null
      - filename             = "./out/inventory.txt" -> null
      ...
    }

  # random_pet.server will be destroyed
  ...
Plan: 0 to add, 0 to change, 2 to destroy.
$ terraform destroy
...
Destroy complete! Resources: 2 destroyed.
terraform plan -destroy
  • terraforminfrastructure as code
  • planpreview changes
terraform destroy
  • destroydelete everything it manages

terraform destroy is the same as terraform apply -destroy: it shows the plan and asks for yes. Terraform destroys in reverse dependency order, the file before the pet it depends on. To remove one resource permanently, delete it from the code and apply; reserve destroy for whole environments such as a feature test or a lab.

In production

Plan and apply from CI, never from laptops: plan on the pull request, apply the saved plan after merge (lesson 13). Protect production with prevent_destroy on stateful resources, and make terraform destroy for production something only a break-glass role can run.

When apply goes wrong

The saved plan is stale. Something changed the state between your plan and your apply: a teammate's apply, a pipeline run or a -replace. The lab reproduced it:

$ terraform apply tfplan

Error: Saved plan is stale

The given plan file can no longer be applied because the state was changed by
another operation after the plan was created.
terraform apply tfplan
  • terraforminfrastructure as code
  • applymake the changes

Fix: this is Terraform protecting you. Plan again, read the new plan, and apply that one.

The state lock is held. Error acquiring the state lock (lesson 8) means another run is active. Wait for it. Use terraform force-unlock <ID> only when you're certain the run that took the lock has died.

Apply fails halfway. Some resources were created, then one failed (a quota, a name already taken, a permission). Terraform saves state for everything that succeeded, so nothing is lost. Read the error, fix the cause in code or in the account, and run plan again: it plans only what's still missing.

⌘
Mini mission

Catch and fix drift

Apply the inventory project, change out/inventory.txt by hand, then use plan to see the drift. Fix it the Terraform way with apply, and confirm a final plan says No changes. Then force a new pet name with -replace and record the old and new names.

Input: main.tf with random_pet.server and local_file.inventoryOutput: ~/drift.txt
Reveal one safe solution
$ terraform apply -auto-approve && cat out/inventory.txt > ~/drift.txt
$ echo "server: hand-edited" > out/inventory.txt
$ terraform plan -no-color | grep -E 'will be|Plan:' >> ~/drift.txt
$ terraform apply -auto-approve && terraform plan -no-color | grep -E 'No changes' >> ~/drift.txt
$ terraform apply -auto-approve -replace=random_pet.server && cat out/inventory.txt >> ~/drift.txt
terraform apply -auto-approve && cat out/inventory.txt > ~/drift.txt
  • terraforminfrastructure as code
  • applymake the changes
  • -auto-approveskip the yes prompt
  • &&run the next command only if this one worked
  • catprint a file
  • >write output to a file, replacing it
echo "server: hand-edited" > out/inventory.txt
  • echoprint text
terraform plan -no-color | grep -E 'will be|Plan:' >> ~/drift.txt
  • planpreview changes
  • |pipe: send output to the next command
  • grepfind lines that match a pattern
  • >>append output to a file

The lab went from server: model-kiwi to server: saved-javelin after the replace. Your names will differ (they're random), but the drift plan should show 1 to add and the final plan "No changes".

Try it yourself

0 of 5 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 4

Why apply a saved plan file instead of running terraform apply on its own?

Go deeper

Official reading for this lesson

  • Docsterraform plan commandHashiCorp ↗
  • Docsterraform apply commandHashiCorp ↗
  • Docsterraform destroy commandHashiCorp ↗
  • DocsResource targetingHashiCorp ↗
  • GuideManage resource driftHashiCorp ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousState: Terraform's memoryNext lesson →Modules: reusable infrastructure