DEV Community

Cover image for Lifecycle rules in Terraform.
Rohan Nalawade
Rohan Nalawade

Posted on

Lifecycle rules in Terraform.

Introduction
Lifecycle rules are used to override the terraform's default behavior.
Lifecycle rules control how terraform creates, destroys, updates a resource.

There are three lifecycle rules in terraform.

  • create before destroy
  • prevent destroy
  • ignore changes

1. Create before destroy
This rule is used to avoid downtime. It is used when creation of new resource is important before deletion of old resource. Suppose you updated the configurations of a EC2 instance and you have applied this rule there. Terraform will create the new resource first and then delete the old resource. This only works if the resource supports parallel existence (for example, multiple EC2 instances or ALB versions). This is helpful to avoid downtime.
This rule is mainly used for ALB, EC2 replacements, ASG.

2. Prevent Destroy
It is used when you want to prevent the accidental deletion of your important resources, such as a S3 bucket. When you run the terraform destroy command and if this rule is applied to the resource, that resource will not get deleted unless and until you change the rule to false. It is mainly used for Critical S3 buckets, Production databases, Important IAM roles, etc.

3. Ignore Changes
It simply ignores the changes to the resource if the change is made from out of terraform. For example you have defined configurations of ASG such as desired capacity, and you have applied the rule of ignore changes to the resource. If ignore_changes is applied and someone modifies the resource outside Terraform (for example via the AWS Console), Terraform will ignore that drift and will not attempt to bring the resource back to the value defined in the Terraform code.

Conclusion
Terraform lifecycle rules provide fine-grained control over how resources are created, updated, and destroyed. By using rules such as create_before_destroy, prevent_destroy, and ignore_changes, you can reduce downtime, protect critical infrastructure, and safely handle changes made outside Terraform. When applied thoughtfully, lifecycle rules help make Terraform-managed infrastructure more reliable, predictable, and production-ready.

Top comments (0)