Resource Lifecycle Meta-Arguments
What you'll learn: How to control exactly when and how Terraform creates, updates, or destroys resources using special lifecycle rules.
What Are Lifecycle Meta-Arguments?
By default, Terraform decides how to manage your resources: it creates them when they don't exist, updates them in-place when possible, and sometimes destroys and recreates them when necessary. But sometimes you need to override this default behavior. That's where lifecycle meta-arguments come in—they let you fine-tune how Terraform handles resource changes.
Think of lifecycle rules as special instructions you give to Terraform: "Wait, don't destroy that yet!" or "Ignore changes to this specific attribute."
The Three Key Lifecycle Rules
create_before_destroy
Normally, Terraform destroys the old resource before creating the new one. With create_before_destroy = true, it creates the replacement first, then destroys the old one. This prevents downtime.
resource "aws_instance" "web" {
# ... other arguments ...
lifecycle {
create_before_destroy = true
}
}
prevent_destroy
This acts as a safety lock—Terraform will refuse to destroy the resource, protecting critical infrastructure from accidental deletion.
lifecycle {
prevent_destroy = true
}
ignore_changes
Sometimes external systems modify your resources. Use ignore_changes to tell Terraform to stop managing specific attributes.
lifecycle {
ignore_changes = [tags, ami]
}
When to Use These Rules
- create_before_destroy: Load balancers, DNS records—anything where downtime hurts
- prevent_destroy: Databases, stateful resources you never want accidentally deleted
- ignore_changes: Auto-scaling tags, timestamps, or attributes managed by other tools
Key Takeaway: Lifecycle meta-arguments give you surgical control over resource behavior, letting you prevent downtime, protect critical resources, and ignore external changes when needed.