Course contentsShow
← Cloud and Infrastructure
Lesson 745 of 2,98914. Terraform FundamentalsFree lesson

Resource Meta-Arguments: lifecycle

Control resource behavior with lifecycle rules like create_before_destroy, prevent_destroy, and ignore_changes.

Resource Meta-Arguments: lifecycle

What You'll Learn

You'll discover how to control resource behavior during creation, updates, and deletion using Terraform's lifecycle meta-argument.

Understanding Lifecycle Rules

By default, Terraform manages resources in a straightforward way: it creates them when you add them to your configuration, updates them in place when possible, and destroys them when you remove them. But sometimes you need more control over how Terraform handles these operations.

The lifecycle meta-argument lets you override Terraform's default behavior with special rules. Think of it like setting house rules for how Terraform can interact with specific resources.

The Three Main Lifecycle Rules

create_before_destroy

When updating a resource requires replacement, Terraform usually destroys the old resource first, then creates the new one. Setting create_before_destroy = true reverses this order—useful when you can't afford downtime.

prevent_destroy

This acts like a safety lock. When prevent_destroy = true, Terraform will refuse to destroy the resource, preventing accidental deletions of critical infrastructure like production databases.

ignore_changes

Sometimes external tools or manual changes modify resources outside Terraform. With ignore_changes, you can tell Terraform to ignore specific attributes during updates, preventing it from constantly trying to "fix" those values.

Example Structure

resource "aws_instance" "web" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"

  lifecycle {
    create_before_destroy = true
    prevent_destroy       = false
    ignore_changes        = [tags]
  }
}

Key Takeaway: The lifecycle meta-argument gives you fine-grained control over resource behavior with create_before_destroy, prevent_destroy, and ignore_changes rules—essential for managing production infrastructure safely.