Introduction
As DevOps engineers, we've all had that heart-stopping moment when Terraform unexpectedly wipes out a piece of infrastructure we spent hours fine-tuning. It's like watching a helpful robot knock over the entire Jenga tower, Terraform not at fault but without caution, its actions might become destructive.
Luckily, Terraform equips us with some solid defenses like lifecycle.prevent_destroy and enable_deletion_protection to help us keep our infrastructure safe from accidental mistakes, surprise recreations, or unintended changes.
Two Solid Ways to Protect Terraform Resources
Lifecycle with prevent_destroy
Within a lifecycle block, setting prevent_destroy = true tells Terraform to flat-out refuse to delete the resource. It's Terraform's way of politely saying, "Nope, at this time!".
Best For: Protecting critical resources like databases or stateful resources where accidental deletion could cause catastrophic data loss.
Usage:
resource "aws_instance" "example" {
ami = "ami-12345678"
instance_type = "t2.micro"
lifecycle {
prevent_destroy = true
}
}lifecycle.prevent_destroy is like a seatbelt; essential, but it won't stop us from manually removing the seat altogether.
We can override prevent_destroy for the entire configuration by running terraform destroy, or selectively target a resource for destruction using terraform destroy -target=<resource>.
Suggestion:
Combine it with other lifecycle controls like ignore_changes and create_before_destroy for tighter safety.
-
ignore_changes: Helps Terraform "look away" from changes it shouldn’t react to. -
create_before_destroy: Makes Terraform build a new house before tearing down the old one.
Cloud Provider Specific: enable_deletion_protection
This setting leverages built-in deletion protection offered by various cloud providers - AWS, Azure, GCP - like AWS's RDS and EC2, or Google's Cloud SQL. Think of it as Terraform delegating protection duties directly to the cloud - smart move!
Best For: Resources directly supported by cloud provider's API for deletion protection. It gives us an extra layer of defense at the cloud provider level.
Usage:
resource "aws_db_instance" "example" {
engine = "mysql"
instance_class = "db.t2.micro"
allocated_storage = 20
storage_type = "gp2"
engine_version = "5.7"
name = "mydb"
enable_deletion_protection = true
}Quick Recommendations
-
lifecycle.prevent_destroy: Our go-to for protecting irreplaceable infrastructure. -
enable_deletion_protection: Use where supported to add cloud-level defense.
Terraform is powerful - We need to just make sure it doesn't "helpfully" clean up more than what's needed! Let's keep our infrastructure safe and our sanity intact.
Happy Terraforming!