plan, apply and destroy

Terraform · Essentials · 8 min

Reading a plan correctly is the single most important safety skill in Terraform.

terraform plan prints each change with a symbol:

  • + create, - destroy, ~ update in place,
  • -/+ replace: destroy then create (or +/- with create first), marked with # forces replacement next to the argument that caused it.

The summary line Plan: 2 to add, 1 to change, 1 to destroy. deserves a pause whenever destroy is non-zero, especially for databases, disks and DNS zones.

terraform apply plans again and asks for confirmation. In automation, save the plan and apply exactly that:

  • terraform plan -out=tfplan then terraform apply tfplan. A saved plan applies only if the state hasn't changed since; it won't silently do something different from what was reviewed.
  • terraform show tfplan (or -json) renders it again.

Other options:

  • -var and -var-file pass variables.
  • -target=aws_instance.web limits the run to one resource and its dependencies: an escape hatch for emergencies, not a workflow.
  • -replace=aws_instance.web forces a resource to be recreated.
  • terraform destroy (or plan -destroy) removes everything in the configuration.

Plans can't see everything: some API errors (quotas, name conflicts) appear only during apply, which then stops part-way. Fix and apply again; Terraform continues from the recorded state.

Example

terraform plan -out=tfplan
#   # aws_db_instance.main must be replaced
# -/+ resource "aws_db_instance" "main" {
#       ~ engine_version = "16.4" -> "17.2" # forces replacement
# Plan: 1 to add, 0 to change, 1 to destroy.

terraform show -no-color tfplan > plan.txt   # attach to the review
terraform apply tfplan
terraform apply -replace=aws_instance.web    # rebuild one VM
terraform plan -destroy                      # preview teardown

Remember

  • + create, ~ update, - destroy, -/+ replace
  • Pause on any destroy or forces replacement
  • plan -out then apply the saved plan in automation

Watch out for

  • Applying without reading the plan and replacing a production database because one argument forces replacement.

Check yourself

  1. A plan line shows -/+ next to a resource. What will happen?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.hashicorp.com/terraform/cli/commands/plan