# prevent_destroy and Other Lifecycle Rules — Terraform

Source: https://www.skillbyai.com/en/terraform/x-protect

> Guard critical resources.

## lifecycle settings

The `lifecycle` block changes how Terraform handles a resource: `prevent_destroy = true` makes any plan that would destroy it fail (protecting databases and state buckets), `create_before_destroy` replaces without a gap, `ignore_changes` stops Terraform reverting attributes changed by something else (such as an autoscaler's desired count), and `replace_triggered_by` forces replacement when another resource changes. Also enable deletion protection at the provider level where it exists.

## A destroy plan blocked by prevent_destroy, 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. Planning a destroy of the protected file fails with "Instance cannot be destroyed". To remove it deliberately you must first change the configuration, which is reviewed like any other change.

```bash
terraform plan -destroy -no-color 2>&1 | grep -E "Error|prevent_destroy"
```

Output:

```
Error: Instance cannot be destroyed
Resource local_file.important has lifecycle.prevent_destroy set, but the plan
with the plan, either disable lifecycle.prevent_destroy or reduce the scope
```

## Combine with provider deletion protection

prevent_destroy only guards Terraform; deletion protection on the database itself also guards against console and API mistakes.

**Quiz:** What does ignore_changes do?

- [ ] Prevents all updates to every resource
- [ ] Deletes the resource
- [ ] Hides the resource from state
- [x] Stops Terraform reverting specified attributes changed outside Terraform

*Answer:* Stops Terraform reverting specified attributes changed outside Terraform. Use it for attributes managed by other systems.
