How to Use Lifecycle in Terraform: Syntax and Examples
In Terraform, use the
lifecycle block inside a resource to control how Terraform handles creation, update, and deletion. Common lifecycle arguments include create_before_destroy, prevent_destroy, and ignore_changes to manage resource replacement and updates safely.Syntax
The lifecycle block is placed inside a resource block to customize resource behavior during Terraform operations.
- create_before_destroy: Ensures a new resource is created before the old one is destroyed.
- prevent_destroy: Stops Terraform from deleting the resource unless overridden.
- ignore_changes: Ignores specified attribute changes to avoid unnecessary updates.
terraform
resource "aws_instance" "example" { ami = "ami-12345678" instance_type = "t2.micro" lifecycle { create_before_destroy = true prevent_destroy = false ignore_changes = ["tags"] } }
Example
This example shows how to use create_before_destroy to avoid downtime when replacing an AWS EC2 instance, and ignore_changes to prevent Terraform from updating tags changed outside Terraform.
terraform
resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t3.micro" tags = { Name = "WebServer" } lifecycle { create_before_destroy = true ignore_changes = ["tags"] } }
Output
Terraform will create the new instance before destroying the old one and will ignore any tag changes made outside Terraform.
Common Pitfalls
Common mistakes when using lifecycle include:
- Setting
create_before_destroywithout ensuring the resource supports it, causing errors. - Using
ignore_changestoo broadly, leading to drift between Terraform state and real infrastructure. - Forgetting
prevent_destroywhen you want to protect critical resources, risking accidental deletion.
terraform
resource "aws_s3_bucket" "example" { bucket = "my-bucket" lifecycle { # Wrong: ignoring all changes can cause drift ignore_changes = ["*"] } } # Correct usage: resource "aws_s3_bucket" "example" { bucket = "my-bucket" lifecycle { prevent_destroy = true } }
Quick Reference
| Lifecycle Argument | Description |
|---|---|
| create_before_destroy | Create new resource before destroying old one to avoid downtime |
| prevent_destroy | Prevent resource deletion unless manually overridden |
| ignore_changes | Ignore changes to specified attributes to avoid unnecessary updates |
Key Takeaways
Use the lifecycle block inside a resource to control creation, update, and deletion behavior.
create_before_destroy helps avoid downtime by creating new resources before deleting old ones.
prevent_destroy protects important resources from accidental deletion.
ignore_changes prevents Terraform from updating attributes changed outside Terraform but use it carefully.
Always test lifecycle settings to ensure they work with your specific resource types.