# Saved Plans and JSON Output — Terraform

Source: https://www.skillbyai.com/en/terraform/p-planfile

> Apply exactly what was reviewed.

## plan -out and show -json

`terraform plan -out=tfplan` saves a plan; `terraform apply tfplan` applies **exactly** that plan, failing if the state changed in between. This is the basis of safe CI workflows: plan on a pull request, review, then apply the saved plan. `terraform show -json tfplan` turns the plan into machine-readable JSON for policy checks (for example, block any destroy of a database) and summaries.

## Summarising a saved plan with jq, run

I ran this with Terraform 1.16.4 and the hashicorp/local 2.9.1 and hashicorp/random 3.9.1 providers, which manage local files and random values, so no cloud account was needed; each example starts from a fresh directory. The saved plan for the for_each and count demo is converted to JSON and summarised as one line per resource change: six creates.

```bash
terraform plan -no-color -out=tfplan >/dev/null
terraform show -json tfplan | jq -r '.resource_changes[] | "\(.change.actions[0]) \(.address)"'
```

Output:

```
create local_file.by_index[0]
create local_file.by_index[1]
create local_file.by_index[2]
create local_file.by_key["api"]
create local_file.by_key["web"]
create local_file.by_key["worker"]
```

## Gate destroys in CI

Scan plan JSON for delete actions on critical resource types and require extra approval when found.

**Quiz:** Why apply a saved plan file in CI?

- [x] It applies exactly what was reviewed and fails if state changed meanwhile
- [ ] It is faster to type
- [ ] It skips providers
- [ ] It deletes the state

*Answer:* It applies exactly what was reviewed and fails if state changed meanwhile. Review and apply the same thing.
