Day-09: Lifecycle management rules in terraform
Source: Dev.to
Lifecycle rules
In Terraform, lifecycle rules control how a resource is created, updated, and destroyed. They help improve security, simplify maintenance, and give you finer control over resources.
Terraform provides six lifecycle arguments:
ignore_changesprevent_destroyreplace_triggered_bycreate_before_destroypreconditionpostcondition
1. create_before_destroy
When a resource needs to be changed, this rule creates the new version before destroying the old one, reducing downtime (zero‑downtime deployment).
// main.tf
resource "aws_instance" "instance" {
ami = "ami-0f64121fa59598bf7"
instance_type = "t3.micro"
region = tolist(var.allowed_region)[0]
tags = var.tags
lifecycle {
create_before_destroy = true
}
}
2. prevent_destroy
Prevents accidental deletion of a resource.
// main.tf
resource "aws_s3_bucket" "bucket" {
bucket = "${var.username}-bucket-${var.environment}-day-09"
lifecycle {
prevent_destroy = true
}
}
3. ignore_changes
Ignores changes made to the resource outside of Terraform (e.g., manual tag edits).
// main.tf
resource "aws_instance" "instance" {
ami = "ami-0f64121fa59598bf7"
instance_type = "t3.micro"
region = tolist(var.allowed_region)[0]
tags = var.tags
lifecycle {
ignore_changes = [tags]
}
}
4. replace_triggered_by
Forces replacement of the resource when a specified attribute changes.
// main.tf
resource "aws_instance" "instance" {
ami = "ami-0f64121fa59598bf7"
instance_type = "t3.micro"
region = tolist(var.allowed_region)[0]
tags = var.tags
lifecycle {
replace_triggered_by = [instance_type]
}
}
5. precondition
Validates a condition before creating or updating the resource.
// main.tf
resource "aws_instance" "instance" {
ami = "ami-0f64121fa59598bf7"
instance_type = "t3.micro"
region = tolist(var.allowed_region)[0]
tags = var.tags
lifecycle {
precondition {
condition = var.instance_type == "t3.micro"
error_message = "Instance type must be t3.micro"
}
}
}
6. postcondition
Validates a condition after the resource has been created or updated.
// main.tf
resource "aws_instance" "instance" {
ami = "ami-0f64121fa59598bf7"
instance_type = "t3.micro"
region = tolist(var.allowed_region)[0]
tags = var.tags
lifecycle {
postcondition {
condition = aws_instance.instance.instance_state == "running"
error_message = "Instance is not in running state"
}
}
}
Best practices
- Use lifecycle rules to manage resources effectively.
- Test lifecycle rules in a non‑production environment before applying them to production.
- Document the lifecycle rules used in the Terraform code for better understanding and maintenance.
- Regularly review and update lifecycle rules as requirements evolve.
- Be cautious with
ignore_changes; it can hide important modifications. - Apply
create_before_destroyto critical resources to avoid downtime.