# 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.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 9. About 30 minutes, beginner. Source: https://devops.rajeev.pro/courses/terraform/09-plan-apply-destroy

## What you will learn

- Explain the three inputs to a plan and read every part of plan output
- Save a plan with -out and apply exactly that plan
- Recognise drift and decide whether to fix the code or let Terraform put it back
- Force a replacement with -replace and know when -target is acceptable
- Destroy safely, and preview it with plan -destroy

> **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. <br />**Code walkthrough:** none. <br />**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.

> **Figure.** Three inputs, your .tf files for the desired state, the state file for what Terraform created, and real resources refreshed through APIs, flow into terraform plan, which computes a diff of actions and can save it with -out. terraform apply tfplan changes reality and then writes state. Side options: -replace to force recreation, -target for one resource in emergencies, and destroy, previewed with plan -destroy. Drift, a manual change, is noticed on refresh and put back.
>
> Plan compares code, state and reality. Apply makes reality match the code, then records it.

## 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:

```text
$ 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"
```

(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

```text
$ 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
```

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:

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

No changes. Your infrastructure matches the configuration.
```

### Drift: when someone changes things by hand

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

```text
$ 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.
```

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.

```text
$ 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.
```

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:

```text
$ 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 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:

```text
$ 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.
```

_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.

## 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.

- You need: main.tf with random_pet.server and local_file.inventory
- You'll have: ~/drift.txt

```sh
$ 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
```

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

- Run `terraform plan -out=tfplan`, then `terraform show tfplan`, then `terraform apply tfplan`.
- Edit a managed file by hand and run `terraform plan` to see the drift.
- Run `terraform apply -replace=random_pet.server` and note the new name.
- Preview a teardown with `terraform plan -destroy`, then run `terraform destroy`.
- Do the mini mission and keep `~/drift.txt`.

## Quiz

1. Why apply a saved plan file instead of running terraform apply on its own?
   - It's faster
   - **It applies exactly the reviewed changes; a plain apply re-plans, and things may have changed since you looked** (answer)
   - Saved plans skip the state lock
   Why: terraform apply tfplan does what was planned or fails if the state changed. That's what makes "plan in the PR, apply after merge" safe.

2. Someone edited a Terraform-managed file by hand. What does the next plan do?
   - Ignores it
   - **Detects the difference during refresh and plans to put it back to match the code** (answer)
   - Deletes the state
   Why: That's drift. Terraform makes reality match the code. If the manual change was right, update the code instead.

3. When is -target acceptable?
   - On every run, to save time
   - **In an emergency or to recover from a mistake, knowing it skips the rest of the plan** (answer)
   - Never
   Why: -target applies a partial plan, which can leave state and code out of step. HashiCorp recommends it only for exceptional situations.

4. What does terraform plan -destroy show?
   - **The resources that would be destroyed, without destroying anything** (answer)
   - It destroys everything immediately
   - Only resources with prevent_destroy
   Why: It's a dry run of destroy. terraform destroy shows the same plan and asks for confirmation.

## Resources

- [terraform plan command](https://developer.hashicorp.com/terraform/cli/commands/plan) (HashiCorp)
- [terraform apply command](https://developer.hashicorp.com/terraform/cli/commands/apply) (HashiCorp)
- [terraform destroy command](https://developer.hashicorp.com/terraform/cli/commands/destroy) (HashiCorp)
- [Resource targeting](https://developer.hashicorp.com/terraform/cli/commands/plan#resource-targeting) (HashiCorp)
- [Manage resource drift](https://developer.hashicorp.com/terraform/tutorials/state/resource-drift) (HashiCorp)
