terraform apply, Terraform will first delete the old file and then create a new one.
By default, Terraform’s update process deletes the existing resource before creating a new one, which may not be desirable in all scenarios.
Understanding Terraform’s Update Mechanism
Consider the following example where we update the file permission of a local file resource:terraform apply command, you might see an output similar to:
Lifecycle Rules
Terraform offers several lifecycle rules to modify this default behavior. These rules can be configured within the resource block to either create the new resource before destroying the old one, prevent resource deletion, or ignore specific attribute changes.The create_before_destroy Rule
Thecreate_before_destroy lifecycle rule instructs Terraform to create a new resource before deleting the old one. This is particularly useful when maintaining service availability is critical.
The prevent_destroy Rule
In some cases, you might want to ensure a resource is never accidentally deleted—even if a configuration change would normally force a replacement. Terraform allows you to achieve this using theprevent_destroy rule.
terraform apply and the plan includes destroying the resource, Terraform will generate an error similar to the following:
Even with
prevent_destroy enabled, running terraform destroy explicitly will still remove the resource. This rule only prevents destruction triggered by configuration changes.The ignore_changes Rule
Theignore_changes rule is beneficial when you want Terraform to disregard modifications made to specific attributes. For example, if an external process updates the tags on an AWS EC2 instance, Terraform can be configured to ignore these changes during subsequent runs.
Consider the following AWS EC2 instance configuration:
ignore_changes rule to the lifecycle block:
all:
Lifecycle Rules at a Glance
Summary
In this article, we reviewed three key lifecycle rules in Terraform:- The create_before_destroy rule ensures uninterrupted resource availability by creating the new resource first.
- The prevent_destroy rule safeguards critical resources from unintentional deletion.
- The ignore_changes rule allows you to specify attributes that Terraform should ignore during state comparisons, accommodating external changes.
