What is create_before_destroy in Terraform: Explanation and Example
create_before_destroy is a lifecycle setting in Terraform that tells it to create a new resource before destroying the old one. This helps avoid downtime by keeping the service available during updates or replacements.How It Works
Imagine you want to replace an old lamp with a new one without leaving the room dark. create_before_destroy works like turning on the new lamp first, then turning off the old one. This way, there is no moment without light.
In Terraform, when you change a resource that requires replacement, normally it destroys the old resource first, then creates the new one. This can cause downtime or service interruption. By enabling create_before_destroy, Terraform creates the new resource first, waits for it to be ready, and only then destroys the old resource.
This setting is part of the resource's lifecycle block and helps keep your infrastructure stable during updates.
Example
This example shows how to use create_before_destroy in a Terraform resource lifecycle to replace an AWS EC2 instance without downtime.
resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" lifecycle { create_before_destroy = true } tags = { Name = "example-instance" } }
When to Use
Use create_before_destroy when you want to update or replace resources without causing downtime. This is especially important for resources that serve live traffic, like servers, load balancers, or databases.
For example, if you update an EC2 instance type or replace a load balancer, enabling this setting ensures the new resource is ready before the old one is removed. This avoids service interruptions and keeps your applications running smoothly.
However, be aware that this may temporarily increase costs because both old and new resources exist simultaneously during the transition.
Key Points
- create_before_destroy creates new resources before deleting old ones.
- It helps avoid downtime during resource replacement.
- Used inside the
lifecycleblock of a resource. - May increase temporary costs due to overlapping resources.
- Best for critical resources that must stay available.
Key Takeaways
create_before_destroy prevents downtime by creating new resources before destroying old ones.lifecycle block in Terraform.