Zero-Downtime Deployment

Terraform’s “create_before_destroy” approach ensures that when updating an existing resource, a new version is first created before the old one is destroyed to minimize downtime and data loss.

A “create before destroy” approach means that when Terraform updates an existing resource, it creates a new version of that resource before destroying the old one. This ensures that there is always a working version of the resource and minimizes the risk of downtime or data loss.

This behavior is enabled by default in Terraform and is referred to as the “create_before_destroy” lifecycle. When a resource is updated, Terraform creates a new resource with the new configuration and waits for it to become ready before destroying the old resource.

If the new resource fails to be created or becomes ready, Terraform will abort the update process and leave the old resource intact. This ensures that a functioning resource is always available, even in the event of an update failure.

The create_before_destroy strategy can be advantageous when making significant changes to infrastructure resources or updating critical components that need to be highly available. By creating a new resource before destroying the old one, Terraform helps ensure that updates are rolled out smoothly without affecting the stability or performance of the infrastructure.

Example of using Terraform to create an AWS EC2 instance with the “create_before_destroy” strategy

resource "aws_instance" "example_instance" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  
  lifecycle {
    create_before_destroy = true
  }
}

The lifecycle block is used to enable the “create_before_destroy” behavior. When this Terraform configuration is applied, it will create a new EC2 instance based on the specified configuration before destroying any existing instances that may have been created with a previous configuration. This helps ensure that the instance is always available and that any potential downtime is minimized.

Last modified July 21, 2024: update (e2ae86c)