Skip to main content

Infrastructure as code · Intermediate · 22 min

Protect important resources with Terraform lifecycle rules

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Terraform 1.17.2 · hashicorp/local 2.9 · hashicorp/random 3.9

You will use prevent_destroy, create_before_destroy, ignore_changes, replace_triggered_by and -replace on a small Terraform configuration, read the plan each one produces, and watch Terraform refuse to destroy a protected resource.

On this page

Most of the time you want Terraform to do exactly what the code says. Change an argument the provider cannot update in place, and Terraform destroys the object and builds a new one. Run terraform destroy, and everything goes. For a throwaway file that is fine. For a production database, a DNS zone or a storage bucket full of customer uploads, one careless plan can cost a day of restore work.

The lifecycle block inside a resource changes those defaults. It has five settings you will use often, and each one answers a different question:

  • prevent_destroy: should Terraform ever be allowed to destroy this?
  • create_before_destroy: when this must be replaced, can the old one stay up until the new one exists?
  • ignore_changes: which arguments belong to someone else after creation?
  • replace_triggered_by: which other change should rebuild this resource?
  • -replace on the command line (not part of lifecycle, but the same family): rebuild this one object now, once.

You will try each on a configuration made of random, local and the built-in terraform_data resource, so nothing reaches a cloud account and nothing bills. A random_pet name stands in for anything that hurts to lose: when one is replaced it gets a new name, so you can see a replacement happen. For every change you save a plan with -out, read it, and only then apply that exact plan.

The demo lives in ~/lifecycle-demo.

Step 1 · Install Terraform 1.17

Install curl and unzip, then download Terraform 1.17.2 for your machine's architecture, check it against HashiCorp's published checksums and put the binary on your PATH:

Bash
sudo apt update
sudo apt install -y curl unzip ca-certificates
TF_VERSION=1.17.2
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_${ARCH}.zip"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "terraform_${TF_VERSION}_SHA256SUMS"
unzip -o "terraform_${TF_VERSION}_linux_${ARCH}.zip" terraform
sudo install -m 0755 terraform /usr/local/bin/terraform
terraform version

A binary installed this way gets no updates from apt. To upgrade, run the same commands with a newer TF_VERSION. If you already have Terraform 1.17 from another tutorial, skip this step.

On metered or prepaid data, set a plugin cache before your first terraform init, so each provider downloads once per machine rather than once per project:

Bash
mkdir -p ~/.terraform.d/plugin-cache
echo 'export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"' >> ~/.bashrc
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"

Check it worked

sha256sum prints terraform_1.17.2_linux_amd64.zip: OK (or arm64), and the first line of terraform version is Terraform v1.17.2.

Step 2 · Build a configuration with four kinds of resource

Each file holds one resource with a different job, so later steps change one file at a time:

  • database.tf: a name for a database you must never lose, plus a config file that records it
  • web.tf: a web server name that is rebuilt whenever the app version changes
  • server.tf: a server whose patched_on label is owned by a patching tool
  • worker.tf: a settings object and a background worker that should restart when the settings change
Bash
mkdir -p ~/lifecycle-demo
cd ~/lifecycle-demo

cat > versions.tf <<'HCL'
terraform {
  required_version = "~> 1.17.0"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.9"
    }
  }
}
HCL

cat > variables.tf <<'HCL'
variable "app_version" {
  description = "Version of the web app. A new version needs a new web server."
  type        = string
  default     = "1.0"
}

variable "patched_on" {
  description = "Date the patching tool last touched the server."
  type        = string
  default     = "2026-11-01"
}

variable "log_level" {
  description = "Log level the worker reads at start-up."
  type        = string
  default     = "info"
}
HCL

cat > database.tf <<'HCL'
resource "random_pet" "database" {
  length = 2
}

resource "local_file" "db_config" {
  filename = "${path.module}/out/database.conf"
  content  = "name=${random_pet.database.id}\n"
}

output "database_name" {
  value = random_pet.database.id
}
HCL

cat > web.tf <<'HCL'
resource "random_pet" "web" {
  length = 2
  keepers = {
    app_version = var.app_version
  }
}
HCL

cat > server.tf <<'HCL'
resource "random_pet" "server" {
  length = 2
  keepers = {
    role       = "web"
    patched_on = var.patched_on
  }
}
HCL

cat > worker.tf <<'HCL'
resource "terraform_data" "app_settings" {
  input = {
    log_level = var.log_level
  }
}

resource "random_pet" "worker" {
  length = 2
}
HCL

cat > outputs.tf <<'HCL'
output "names" {
  value = {
    web    = random_pet.web.id
    server = random_pet.server.id
    worker = random_pet.worker.id
  }
}
HCL

keepers on a random_pet is a map that forces a new name whenever any value in it changes. That makes it a stand-in for a cloud argument that cannot be updated in place, such as an instance's machine image. Initialise, plan and apply:

Bash
terraform init
terraform plan -out=tfplan
terraform apply tfplan
terraform output

Check it worked

The apply ends with Apply complete! Resources: 6 added, 0 changed, 0 destroyed. terraform output prints database_name and a names map holding three more names, each two words joined by a hyphen, something like "steady-otter". Keep that output open in another window: you will compare names after each change. cat out/database.conf prints the database name.

Step 3 · Refuse destruction with prevent_destroy

Add prevent_destroy to the database. Rewrite database.tf with a lifecycle block:

Bash
cd ~/lifecycle-demo
cat > database.tf <<'HCL'
resource "random_pet" "database" {
  length = 2

  lifecycle {
    prevent_destroy = true
  }
}

resource "local_file" "db_config" {
  filename = "${path.module}/out/database.conf"
  content  = "name=${random_pet.database.id}\n"
}

output "database_name" {
  value = random_pet.database.id
}
HCL
terraform plan

Adding the rule changes nothing in the real world, so the plan reports No changes. Now try to tear everything down:

Bash
terraform destroy

Terraform stops while planning, before it asks for confirmation. The error names the resource and the rule. The whole plan is rejected, not only the database's part, so the other five resources survive too.

The same check catches the more common accident: an edit that forces a replacement. A replacement is a destroy followed by a create, so changing length = 2 to length = 3 on the database would fail in the same way. That is the main job of prevent_destroy on a real database: a teammate changes an argument that the provider can only apply by rebuilding, and the plan fails instead of quietly scheduling a data loss.

Check it worked

terraform destroy exits with Error: Instance cannot be destroyed, and a line saying random_pet.database has lifecycle.prevent_destroy set. terraform state list still shows six resources and cat out/database.conf still prints the same name.

Step 4 · See what prevent_destroy does not protect

prevent_destroy lives in the resource block, and Terraform does not record it in the state. Delete the block and the protection goes with it: Terraform sees a resource in state with no code behind it, and plans an ordinary destroy.

Try it without applying anything. Move database.tf out of the configuration, plan, then put it back:

Bash
cd ~/lifecycle-demo
mv database.tf database.tf.off
terraform plan -out=tfplan

Read the plan, then do not apply it. It plans to destroy random_pet.database and local_file.db_config, and the database_name output disappears with them, with no error. Restore the file and throw the plan away:

Bash
mv database.tf.off database.tf
rm tfplan
terraform plan

Three habits cover the gap:

  • Read every plan for destroy. In a pipeline, fail the job if the JSON plan (terraform show -json tfplan) contains a delete action for a resource you care about.
  • Use a removed block, not deletion, when a resource leaves the code. With lifecycle { destroy = false }, Terraform forgets the object and leaves it running. /tutorials/move-resources-without-recreating-them-using-moved-blocks shows how.
  • Turn on the provider's own protection as well. Most cloud databases have a deletion-protection argument enforced by the cloud API. That holds even when someone runs a destroy from an old branch or deletes the block.

Check it worked

The plan with database.tf.off ended with Plan: 0 to add, 0 to change, 2 to destroy. and no error. After you put the file back, terraform plan shows No changes. and ls shows database.tf again.

Step 5 · Keep the old object until its replacement exists

The web server's name is rebuilt whenever app_version changes. By default Terraform destroys the old one first and then creates the new one, leaving a gap. Set version 1.1 in a variables file and look at the plan:

Bash
cd ~/lifecycle-demo
cat > terraform.tfvars <<'HCL'
app_version = "1.1"
HCL
terraform plan -out=tfplan

The plan marks random_pet.web with -/+, explained in the legend as destroy and then create replacement. On a load balancer, a certificate or a server behind DNS, that order means a few minutes of errors for your users.

Add create_before_destroy and plan again:

Bash
cat > web.tf <<'HCL'
resource "random_pet" "web" {
  length = 2
  keepers = {
    app_version = var.app_version
  }

  lifecycle {
    create_before_destroy = true
  }
}
HCL
terraform plan -out=tfplan

The symbol flips to +/-, create replacement and then destroy. Apply the saved plan:

Bash
terraform apply tfplan
terraform output names

Before you use this on a cloud resource, check that two copies can exist at once. Many resources need a unique name, and the new one fails to create while the old one still holds it. The usual fix is a name prefix or a random suffix so the two never collide. Terraform also turns on create_before_destroy for anything this resource depends on, so you cannot switch it off on those.

Check it worked

The second plan shows +/- for random_pet.web and Plan: 1 to add, 0 to change, 1 to destroy. After the apply, terraform output names shows a new web name, the same server and worker names, and terraform output database_name is unchanged.

Step 6 · Hand one argument to another tool with ignore_changes

On a cloud server, a patching agent or a cost tool often writes its own tags, such as patched_on. Terraform reads the object back, sees a tag that the code does not set, and plans to remove it. On the next agent run the tag comes back, and the two tools fight forever.

ignore_changes tells Terraform that an argument is set at creation and then left alone. It covers differences from either side: an outside tool changing the object, or a new value arriving in your code. The local providers here cannot be changed from outside, so you will see the code side. Pass a new patch date, as a patching pipeline would:

Bash
cd ~/lifecycle-demo
cat > terraform.tfvars <<'HCL'
app_version = "1.1"
patched_on  = "2026-11-20"
HCL
terraform plan -out=tfplan

A new date forces a whole new server, which is far worse than a tag being rewritten. Do not apply. Tell Terraform to ignore that one key of keepers, leaving role under its control:

Bash
cat > server.tf <<'HCL'
resource "random_pet" "server" {
  length = 2
  keepers = {
    role       = "web"
    patched_on = var.patched_on
  }

  lifecycle {
    ignore_changes = [keepers["patched_on"]]
  }
}
HCL
terraform plan
terraform output names

The square-bracket form picks one key of a map. On a cloud server resource the line would be ignore_changes = [tags["patched_on"]], which leaves every other tag under Terraform's control. ignore_changes = all ignores every argument, so Terraform still creates and destroys the object but never updates it. Use that sparingly: drift you never see is drift you never fix.

Check it worked

The first plan marked random_pet.server with must be replaced. After you add ignore_changes, terraform plan reports No changes. and terraform output names shows the same server name as before.

Step 7 · Rebuild one resource when another changes

The worker reads its settings only when it starts, so a new log level means nothing until the worker restarts. Nothing in the worker's own arguments changes, so Terraform has no reason to touch it. replace_triggered_by links the two: when the referenced resource is updated or replaced, this one is replaced as well.

replace_triggered_by accepts references to managed resources only, not plain variables. The terraform_data resource holds the settings so that they have a lifecycle of their own. Rewrite worker.tf, then change the log level:

Bash
cd ~/lifecycle-demo
cat > worker.tf <<'HCL'
resource "terraform_data" "app_settings" {
  input = {
    log_level = var.log_level
  }
}

resource "random_pet" "worker" {
  length = 2

  lifecycle {
    replace_triggered_by = [terraform_data.app_settings]
  }
}
HCL
terraform plan

Adding the trigger on its own plans nothing. Now set log_level to debug:

Bash
cat > terraform.tfvars <<'HCL'
app_version = "1.1"
patched_on  = "2026-11-20"
log_level   = "debug"
HCL
terraform plan -out=tfplan
terraform apply tfplan
terraform output

terraform_data.app_settings is updated in place, and the plan says random_pet.worker will be replaced because of a change in replace_triggered_by. To trigger on one attribute rather than any change to the resource, reference it directly, for example terraform_data.app_settings.output.

Check it worked

The plan reads Plan: 1 to add, 1 to change, 1 to destroy. After the apply, only the worker name in terraform output is new.

Step 8 · Force a single replacement with -replace

Sometimes an object is broken in a way Terraform cannot see: a server with a corrupted disk, a worker stuck after a bad deploy. The code is right, so there is nothing to edit. -replace plans a replacement of one address for this run only:

Bash
cd ~/lifecycle-demo
terraform plan -replace=random_pet.worker -out=tfplan
terraform apply tfplan
terraform output

The plan says the worker will be replaced as requested. Nothing is written to your code or state beforehand, so a colleague's plan the next morning is unaffected. -replace replaces the older terraform taint, which is deprecated because it changed the state before anyone saw a plan.

prevent_destroy still wins. Try to force a new database:

Bash
terraform plan -replace=random_pet.database

Check it worked

After the first apply, the worker name has changed again and database_name, web and server are the same. The database plan fails with Error: Instance cannot be destroyed.

Step 9 · Lift the protection and clean up

To destroy a protected resource on purpose, change the code first, so the decision goes through review like any other change. Set prevent_destroy = false in database.tf:

Bash
cd ~/lifecycle-demo
cat > database.tf <<'HCL'
resource "random_pet" "database" {
  length = 2

  lifecycle {
    prevent_destroy = false
  }
}

resource "local_file" "db_config" {
  filename = "${path.module}/out/database.conf"
  content  = "name=${random_pet.database.id}\n"
}

output "database_name" {
  value = random_pet.database.id
}
HCL
terraform plan -destroy -out=tfplan
terraform apply tfplan

The next command deletes the whole demo folder, including its state. Check that the path is ~/lifecycle-demo before you run it:

Bash
cd ~
rm -rf ~/lifecycle-demo

If you installed Terraform only for this tutorial, remove the binary and the plugin cache, and delete the TF_PLUGIN_CACHE_DIR line from ~/.bashrc:

Bash
sudo rm -f /usr/local/bin/terraform
rm -rf ~/.terraform.d/plugin-cache

Check it worked

The apply ends with Apply complete! Resources: 0 added, 0 changed, 6 destroyed. ls ~/lifecycle-demo reports No such file or directory.

Next steps

  • Rename and restructure resources without a single replacement in /tutorials/move-resources-without-recreating-them-using-moved-blocks.
  • Apply lifecycle rules across many instances at once in /tutorials/repeat-resources-with-count-for-each-and-dynamic-blocks.
  • Stop bad inputs before they reach a plan in /tutorials/check-inputs-with-validation-preconditions-and-check-blocks.
  • Bring hand-made resources under Terraform, then protect them, in /tutorials/import-existing-cloud-resources-into-terraform.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.