Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Providers and Resources

Lifecycle Rules and Provisioners

Control resource behavior with the Terraform lifecycle block: create_before_destroy, prevent_destroy, ignore_changes, replace_triggered_by and conditions, plus provisioners and terraform_data.

By default Terraform applies a simple policy: create what is new, update what changed, replace what cannot be updated, destroy what was removed. Real life needs exceptions. A production database must not be deleted by a typo. A load balancer should be replaced without downtime. An autoscaler changes a desired_capacity that Terraform should not fight. The lifecycle block lets you adjust the default policy for one resource. This lesson also covers provisioners, the escape hatch for running scripts, and why you should rarely use them.

HCL stays read-only; the Python stand-ins imitate how lifecycle rules change a plan.

The lifecycle block

It goes inside any resource and accepts these settings:

HCL
resource "aws_db_instance" "main" {
  # ...

  lifecycle {
    prevent_destroy       = true
    create_before_destroy = false
    ignore_changes        = [tags["LastScan"], allocated_storage]
    replace_triggered_by  = [aws_security_group.db.id]
  }
}

Lifecycle arguments must be literal values, not references to variables, because Terraform needs them before it evaluates the rest.

prevent_destroy

With prevent_destroy = true, any plan that would destroy the resource fails with an error instead of proceeding:

TEXT
Error: Instance cannot be destroyed
  on main.tf line 12:
  Resource aws_db_instance.main has lifecycle.prevent_destroy set, but the plan
  calls for this resource to be destroyed.

(Example output.) It guards against accidental terraform destroy, removing the block, or an edit that forces replacement. It does not stop someone from deleting the object in the console or removing the lifecycle setting first, so it is a seatbelt, not a lock. Put it on databases, state buckets and encryption keys.

create_before_destroy

When a change forces replacement, Terraform normally destroys the old object and then creates the new one, which means a gap. With create_before_destroy = true the order flips: the new object is created first, dependents are updated to point to it, and then the old one is removed. This gives zero-downtime replacement for things such as certificates, launch templates and load balancer target groups.

Watch out for names that must be unique: the old and new objects exist at the same time, so a fixed name collides. Use name_prefix (the provider generates a unique suffix) or include a random part in the name.

HCL
resource "aws_lb_target_group" "app" {
  name_prefix = "app-"
  port        = 80
  protocol    = "HTTP"
  vpc_id      = aws_vpc.main.id

  lifecycle {
    create_before_destroy = true
  }
}

The setting propagates: if resource B depends on A and A has create_before_destroy, Terraform applies the same order to B where needed.

Python Replacement order: default versus create_before_destroy (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

ignore_changes

Some attributes are changed by something other than Terraform: an autoscaler adjusts desired_capacity, a deployment tool updates a task definition's image, a security scanner adds a tag. If you leave it alone, every plan wants to revert the change. ignore_changes tells Terraform to disregard differences in the named arguments after creation:

HCL
resource "aws_autoscaling_group" "web" {
  min_size         = 2
  max_size         = 10
  desired_capacity = 2

  lifecycle {
    ignore_changes = [desired_capacity]
  }
}

The initial value is still used at creation; later edits to it in your code are ignored too, which surprises people. You can ignore a whole map (ignore_changes = [tags]) or individual keys (tags["Owner"]). The special value all ignores everything, which is almost always a mistake because it turns the resource into "create once".

Python ignore_changes hides drift from the plan (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

replace_triggered_by

Replace a resource whenever another resource (or one of its attributes) changes, even if nothing in its own arguments changed. A typical use: recreate servers when a configuration object they depend on only indirectly is replaced:

HCL
resource "aws_instance" "app" {
  # ...
  lifecycle {
    replace_triggered_by = [aws_launch_template.app.latest_version]
  }
}

Combined with terraform_data (below) it provides "re-run when this input changes".

Preconditions and postconditions

Lifecycle blocks can carry custom checks that fail the plan or apply with your message:

HCL
data "aws_ami" "app" {
  # ...
}

resource "aws_instance" "app" {
  ami = data.aws_ami.app.id

  lifecycle {
    precondition {
      condition     = data.aws_ami.app.architecture == "x86_64"
      error_message = "The AMI must be x86_64 for this instance type."
    }
    postcondition {
      condition     = self.public_ip != ""
      error_message = "The instance did not receive a public IP."
    }
  }
}

A precondition is checked before the resource is changed; a postcondition after, using self to refer to the created object. They turn assumptions into explicit failures. Variables have a related feature, validation blocks, covered in Variable Validation.

Provisioners: the last resort

A provisioner runs a script as part of creating or destroying a resource.

HCL
resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  provisioner "local-exec" {
    command = "echo ${self.private_ip} >> inventory.txt"
  }

  provisioner "remote-exec" {
    inline = ["sudo apt-get update", "sudo apt-get install -y nginx"]
    connection {
      type        = "ssh"
      user        = "ubuntu"
      host        = self.public_ip
      private_key = file(var.ssh_key_path)
    }
  }
}
  • local-exec runs a command on the machine running Terraform.
  • remote-exec runs commands on the new resource over SSH or WinRM.
  • file copies a file to the resource.
  • when = destroy runs the provisioner before the resource is destroyed; on_failure = continue ignores errors (default is fail).

HashiCorp's own documentation calls provisioners a last resort, and you should believe it. Terraform cannot model them: they are not in the plan, cannot be previewed, and if one fails the resource is marked tainted and will be replaced on the next apply. Prefer these alternatives:

Need Better option
Install software on a VM A prebuilt image (Packer) or user_data / cloud-init
Configure a server Ansible, run after Terraform, see Ansible
Run a one-off API call A provider resource, or terraform_data with local-exec
Pass data to an app Parameter store, secrets manager, instance metadata

terraform_data

terraform_data is a built-in resource (Terraform 1.4+) that replaces the old null_resource. It does nothing itself, but stores a value, can be a trigger, and can host provisioners:

HCL
resource "terraform_data" "migrate" {
  triggers_replace = [aws_db_instance.main.id, filemd5("${path.module}/schema.sql")]

  provisioner "local-exec" {
    command = "psql -h ${aws_db_instance.main.address} -f schema.sql"
  }
}

The provisioner re-runs only when triggers_replace changes. Use it sparingly for glue tasks that no provider can do.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does prevent_destroy = true do?

    It is a safeguard inside Terraform only: plans containing a destroy for that resource are rejected.
  2. 2. When is create_before_destroy most useful?

    The replacement is created first and dependents are switched over before the old object is deleted.
  3. 3. An autoscaler changes desired_capacity outside Terraform. How do you stop Terraform from reverting it?

    ignore_changes makes Terraform disregard differences in the listed arguments after creation.
  4. 4. Why are provisioners considered a last resort?

    Provisioners are outside Terraform's declarative model, so prefer images, cloud-init, Ansible or provider resources.

Summary

  • lifecycle adjusts a resource's default behavior and accepts only literal values.
  • prevent_destroy blocks destroying plans; create_before_destroy replaces without a gap (watch unique names).
  • ignore_changes stops Terraform from reverting changes made by other systems.
  • replace_triggered_by forces replacement when another object changes; precondition and postcondition assert assumptions.
  • Provisioners (local-exec, remote-exec, file) are a last resort; prefer images, cloud-init, configuration tools or terraform_data.

Next: Input Variables