
Default Behavior in Terraform
By default, when a resource attribute (like an AMI for an EC2 instance) changes, Terraform destroys the existing resource and creates a new one. Consider the following basic EC2 instance configuration:terraform apply leads to the existing instance being destroyed first, followed by the creation of a new one.
Using Lifecycle Rules to Control Resource Behavior
Terraform allows you to modify the default behavior with lifecycle rules. Below are some common lifecycle rules and their use cases.1. Create Before Destroy
To ensure a new resource is created before destroying the current one, you can use thecreate_before_destroy lifecycle rule. This ensures minimal downtime during updates.
When updating critical resources, using
create_before_destroy can help maintain availability.terraform apply now creates a new instance before terminating the old one:
2. Prevent Destroy
For critical resources that should never be deleted accidentally, theprevent_destroy lifecycle rule comes into play. Adding this rule causes Terraform to reject any plan that would destroy a protected resource.
Remember,
prevent_destroy only protects against deletions during configuration changes with terraform apply. It does not override the terraform destroy command.3. Ignore Changes
In some scenarios, you might not want Terraform to act on certain changes. For example, if you prefer that changes to the instance’s tags not trigger an update, use theignore_changes rule:
ignore_changes set for tags, any modifications to the tags—whether from your configuration file or directly on the resource—will be disregarded during the next apply. An example output might be:
all keyword to ignore all changes to a resource.
Conclusion
Terraform lifecycle rules provide flexibility to control resource updates, replacements, and destruction. By strategically using rules likecreate_before_destroy, prevent_destroy, and ignore_changes, you can minimize downtime and safeguard critical infrastructure.
That concludes this overview of Terraform lifecycle rules. Please proceed to the multiple-choice quiz for this section.