Nov 23, 20267 min read

Terraform prevent_destroy and Other Lifecycle Rules

What Terraform's prevent_destroy protects, the gap when a resource block is deleted, why it cannot be a variable, the provider-level deletion protection that closes the gap on AWS, and the other lifecycle rules: create_before_destroy, ignore_changes, replace_triggered_by and conditions.

Illustration for Terraform prevent_destroy and Other Lifecycle Rules

prevent_destroy is the line people add to a Terraform database right after a scary plan, and it does stop a plan that would replace the instance. It does not stop the case that hurts most, a pull request that deletes the resource block, since the setting lives inside the block and disappears with it.

This guide covers what each lifecycle rule protects and the AWS settings that close the gaps.

What does prevent_destroy protect against?

With prevent_destroy = true, Terraform rejects any plan that would destroy the object and returns an error. That covers a change to an argument that forces replacement, such as a new identifier on an RDS instance or a different engine, and a terraform destroy run against the whole configuration:

resource "aws_db_instance" "orders" { identifier = "acme-orders" engine = "postgres" engine_version = "17" instance_class = "db.t4g.medium" allocated_storage = 50 deletion_protection = true skip_final_snapshot = false final_snapshot_identifier = "acme-orders-final" lifecycle { prevent_destroy = true } }

A plan that tries to replace it stops with "Instance cannot be destroyed", naming the resource. The lifecycle docs call it protection for objects that are costly to reproduce, such as databases and storage, and also tell you to use it sparingly, since it blocks some configuration changes and makes terraform destroy fail for the whole configuration.

Where does prevent_destroy fall short?

The documentation states the main gap directly: the rule does not prevent Terraform from destroying a resource if you remove its configuration. Delete the aws_db_instance.orders block, or the module call that contains it, and the plan shows a destroy with no error, since there is no longer a lifecycle block to check. That is the shape of most accidents, a refactor that moved a resource without a moved block or a cleanup PR that removed a module.

Two more limits catch teams out:

  • No variables. Lifecycle arguments only accept literal values, as Terraform reads them while building the graph, so prevent_destroy = var.is_prod is an error. Protection is either on for every environment that uses the block or written as separate blocks.
  • Only Terraform. The rule lives in your configuration, so a delete from the console, the CLI or another tool is not affected.

Which provider settings close the gap on AWS?

Protection that lives in AWS survives a deleted block, so production stateful resources should have both:

ResourceSettingEffect
RDS / Auroradeletion_protection = trueAWS rejects the delete call until it is turned off
RDS / Auroraskip_final_snapshot = falseA final snapshot is taken before deletion
S3 bucketforce_destroy = false (default)Deleting a non-empty bucket fails
DynamoDBdeletion_protection_enabled = trueTable delete is rejected
Account levelAn SCP denying deletes on tagged resourcesBlocks deletes from any tool

With RDS deletion protection, even a plan that destroys the instance fails at apply, since AWS refuses the API call until someone changes the setting, which is a deliberate and reviewable step. The final snapshot is the fallback if both layers are turned off on purpose and it turns out to be a mistake.

When should you use create_before_destroy?

Some changes force a replacement that is fine as long as there is no gap, for example a launch template, a certificate or a security group attached to running instances. create_before_destroy reverses the default order:

resource "aws_acm_certificate" "api" { domain_name = "api.acme.dev" validation_method = "DNS" lifecycle { create_before_destroy = true } }

It only works for resources that can exist twice at the same time, so names that must be unique, such as an S3 bucket name or an RDS identifier, need a generated suffix or name_prefix first. The setting also spreads to the resources that depend on it, since Terraform has to replace them in the same order.

When should you use ignore_changes?

ignore_changes tells Terraform to stop correcting specific attributes that something else manages. The usual cases are a desired count changed by autoscaling, tags added by a cost tool, or a task definition revision that a deploy pipeline updates:

resource "aws_ecs_service" "api" { name = "api" cluster = aws_ecs_cluster.main.id task_definition = aws_ecs_task_definition.api.arn desired_count = 2 lifecycle { ignore_changes = [desired_count, task_definition] } }

Without it, every plan shows a diff that undoes the scaling or the latest deploy, and people learn to skim plans, which is worse. Avoid ignore_changes = all except for resources that are only created by Terraform and fully managed elsewhere.

What do replace_triggered_by and conditions add?

replace_triggered_by, added in Terraform 1.2, replaces a resource when another one changes, which is useful for instances that only read their configuration at boot. precondition and postcondition blocks check assumptions during plan and apply, so a plan can fail early with a readable message:

resource "aws_db_instance" "orders" { # ... lifecycle { prevent_destroy = true precondition { condition = var.environment != "prod" || var.multi_az error_message = "Production databases must run Multi-AZ." } } }

Conditions are a cheap place to encode rules like "production databases are Multi-AZ" that reviewers would otherwise have to remember. They complement prevent_destroy rather than replace it, since they only run while the block exists too.

How does Encore protect databases and buckets from deletion?

Encore

Encore brings infrastructure from code, and its deletion rules cover exactly the case prevent_destroy misses. Per the managing infrastructure docs, stateful resources, meaning databases, buckets and queues, are never deleted unless the application no longer uses them and a user has manually confirmed the deletion. Removing a database declaration from the code therefore does not delete the database on the next deploy, and on your own cloud, SQL databases also get deletion protection at the provider level, which has to be turned off in the cloud console before the resource can be removed.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create orders-api --example=ts/hello-world$ cd orders-api && mkdir -p orders/migrations

The orders database from the Terraform example, declared in the service that uses it:

// orders/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("orders");

The migration for the orders table:

-- orders/migrations/1_orders.up.sql CREATE TABLE orders ( id BIGSERIAL PRIMARY KEY, customer_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'placed', created_at TIMESTAMPTZ NOT NULL DEFAULT now() );

Then the endpoints:

// orders/orders.ts import { api, APIError } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; const db = new SQLDatabase("orders", { migrations: "./migrations" }); interface Order { id: number; customerID: string; status: string; } export const get = api( { expose: true, method: "GET", path: "/orders/:id" }, async ({ id }: { id: number }): Promise<Order> => { const row = await db.queryRow<{ id: number; customer_id: string; status: string }>` SELECT id, customer_id, status FROM orders WHERE id = ${id} `; if (!row) throw APIError.notFound("order not found"); return { id: row.id, customerID: row.customer_id, status: row.status }; }, );

encore run starts Postgres locally and applies the migration. On deploy to your AWS account, Encore provisions the database on RDS and an IAM role for the service, or a service account on GCP. The other safeguards in the same docs sit outside the code: only Admins can destroy an environment, which also requires typing a confirmation, and production environments can require infrastructure approval before any deploy that changes infrastructure, including IAM.

The split matters once coding agents write the code, since an agent can add a table or a second database in the service and test it with encore run, and a change that drops a database from the code still cannot delete it without a person confirming in the dashboard.

Best fit: Teams that want production databases and buckets protected against deleted code by default, with infrastructure changes approved by a person before they deploy.

Terraform lifecycle checklist

  • Put prevent_destroy = true on production databases, buckets and other stateful resources.
  • Add provider protection as well: deletion_protection, final snapshots and force_destroy = false.
  • Remember that a deleted resource block removes prevent_destroy with it, and read plans for destroys.
  • Use create_before_destroy only for resources that can exist twice.
  • Limit ignore_changes to attributes another system manages.
  • Encode environment rules as precondition blocks.

Frequently asked questions

Does prevent_destroy stop a resource from being deleted if I remove it from the config?

No. prevent_destroy only applies while the resource block exists. If the block is deleted, the setting goes with it and the next apply destroys the object, so pair it with provider-level protection such as deletion_protection on RDS.

Can I set prevent_destroy with a variable?

No. Lifecycle arguments only accept literal values, since Terraform evaluates them while building the dependency graph. Teams that want protection only in production usually keep it on everywhere or use separate resource blocks per environment.

How do I destroy a resource that has prevent_destroy set?

Change prevent_destroy to false or remove the lifecycle argument in a reviewed change, apply, and then destroy. For an RDS instance with deletion_protection, turn that off in the same way first, since AWS rejects the delete call while it is on.

What is the difference between prevent_destroy and create_before_destroy?

prevent_destroy makes a plan fail if it would destroy the object. create_before_destroy changes the order of a replacement, so Terraform creates the new object before deleting the old one, which avoids downtime for resources that can exist twice.

How does Encore protect production databases from being destroyed?

Stateful resources such as databases and buckets are not deleted because their declaration left a pull request: they stay until they are unused and a person confirms deletion in the dashboard. Production environments can also require infrastructure approval before a deploy that changes infrastructure.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders