In this lesson, we’ll dive into OpenTofu’s lifecycle rules to control how resources are created, updated, or destroyed. Proper use of these rules helps you avoid downtime, accidental deletions, and unnecessary modifications.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Table of Contents
- Default Behavior
- create_before_destroy
- prevent_destroy
- ignore_changes
- Summary of Lifecycle Rules
- Further Reading
Default Behavior
By default, OpenTofu will destroy and then recreate any resource if a change requires replacement (for example, updating an AMI in anaws_instance).
ami value and running tofu apply, you’ll see:
1. create_before_destroy
Usecreate_before_destroy = true to provision the replacement resource before tearing down the old one. This helps minimize downtime.
tofu apply now provisions the new instance first:
2. prevent_destroy
Setprevent_destroy = true to block any accidental deletion during an apply. OpenTofu will throw an error if a change requires replacement.
tofu apply, you’ll get:
prevent_destroy does not block a direct tofu destroy. It only prevents destruction during apply operations triggered by configuration changes.3. ignore_changes
Theignore_changes meta-argument instructs OpenTofu to skip tracking specified attributes, even if they drift from your configuration.
Name tag manually in the AWS console, tofu apply reports no changes:
Use
ignore_changes = all cautiously. Ignoring all drift may mask unintended configuration drift over time.Summary of Lifecycle Rules
| Rule | Description | Example |
|---|---|---|
| create_before_destroy | Provision the new resource before destroying the old to minimize downtime. | create_before_destroy = true |
| prevent_destroy | Block any destructive change during apply, protecting critical resources. | prevent_destroy = true |
| ignore_changes | Skip specific attribute changes or all drift between config and real-world state. | ignore_changes = [tags] or all |
| Default (no lifecycle) | Replace resources by destroying then recreating whenever a change requires resource replacement. | N/A |