Terraform Life Cycle Rule
Video link: Here.
Terraform lifecycle rules are directives within a resource block that allow you to customise how Terraform manages the creation, update, and destruction of infrastructure resources. These rules help us control resource behaviour to minimise downtime, prevent accidental deletions, and ignore certain attribute changes.
Life cycle rules
ignore_changes: The
ignore_changesrule tells Terraform to disregard changes to specific attributes of a resource during state comparisons. This is useful when external processes or manual changes modify attributes that you don’t want Terraform to revert or manage. For example, if tags on an AWS EC2 instance are updated manually, you can useignore_changesto prevent Terraform from trying to change them back on the next run.create_before_destroy: With
create_before_destroyTerraform creates a new resource before deleting the old one. This is especially helpful for minimising downtime during updates, such as replacing a database instance or updating a load balancer. Terraform ensures the new resource is fully provisioned and ready before removing the old one.prevent_destroy: The
prevent_destroyrule stops Terraform from destroying a resource, even if you remove it from your configuration or run aterraform destroy. This is useful for protecting critical infrastructure, like production databases, from accidental deletion.replace_triggered_by:
replace_triggered_byallows you to specify attributes whose changes will trigger a resource replacement instead of an in-place update. This is helpful when certain attribute changes require a new resource to be created (for example, changing a subnet for an AWS instance that doesn’t support in-place updates).Pre and Post Condition: Precondition and postcondition blocks let you add validation logic before or after resource actions. A precondition runs before the resource is created, updated, or destroyed, and if it fails, Terraform halts the operation. A postcondition runs after the action, allowing you to verify the outcome. These are useful for enforcing policies or checking that external dependencies are in place.
These rules give you fine-grained control over how Terraform manages your infrastructure, helping you avoid unwanted changes, downtime, and accidental deletions.
You can refer code for each configuration in this repo: Repo.
Arigato!