π― Goal: Go beyond basic resources β use lifecycle rules to build self-healing, zero-downtime, audit-proof infrastructure.
β Youβll master:
- β
create_before_destroyβ zero-downtime updates- β
prevent_destroyβ stop accidentalterraform destroy- β
ignore_changesβ coexist with external tools (ASG, monitoring)- β
replace_triggered_byβ force rebuilds on dependency changes- β
precondition/postconditionβ enforce compliance before & after apply
β Without lifecycle rules:
terraform applyβ destroys DB β creates new β 60s downtimeterraform destroyβ deletes prod S3 bucket β irrecoverable data loss- ASG scales to 100 β
terraform planβ wants to revert to 2 β fighting your tools
β With lifecycle rules:
β Infrastructure that protects itself
β Zero-downtime deployments by default
β Safe coexistence with external systems
| Rule | Use Case | Risk if Missing | Production Ready? |
|---|---|---|---|
create_before_destroy = true |
EC2, RDS, ASG | Downtime during updates | β Critical for stateful resources |
prevent_destroy = true |
Prod DBs, S3 buckets, IAM roles | Accidental deletion = outage | β Non-negotiable for critical resources |
ignore_changes = [attr] |
ASG desired_capacity, EC2 tags |
Terraform fights external tools | β Essential for hybrid infra |
replace_triggered_by = [...] |
Rebuild instances on SG/AMI change | Stale configs, security gaps | β Key for immutable infra |
precondition |
Enforce region/tag policies before create | Invalid resources get created | β Guardrails for standards |
postcondition |
Verify tags/compliance after create | Deployed resources donβt meet policy | β Audit-proof deployments |
π― Golden Rule:
βIf your resource holds data or serves traffic β it needs lifecycle rules.β
variables.tf β Setupvariable "allowed_regions" {
type = set(string)
default = ["us-east-1", "us-west-2"]
}
variable "compliance_tags" {
type = list(string)
default = ["Environment", "Compliance", "Owner"]
}
create_before_destroy β Zero-Downtime EC2main.tf