liveBook · Manning

Create_before_destroy

As explained in Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu

create_before_destroy is a Terraform lifecycle setting that causes a replacement object to be created before the existing object is destroyed.

create_before_destroy is a Terraform lifecycle setting for replacements. Instead of destroying the existing object first, Terraform creates the replacement before removing the old object. section 2.7.2

Use the setting with these operational trade-offs:

  • Terraform normally destroys the existing object before creating its replacement. section 2.7.2
  • Creating both objects temporarily can fail when infrastructure requires unique identifiers or cannot be shared, such as IAM role names or elastic IP addresses. section 2.7.2
  • The setting is useful when high availability makes even a brief resource outage unacceptable. section 2.7.2
  • Declare it inside a resource’s single lifecycle block; lifecycle blocks cannot be repeated for the same resource or data source. section 2.7.2
Listing 2.27 create_before_destroy example
resource "aws_instance" "hello_world" {
  ami           = data.aws_ami.ubuntu.id
  subnet_id     = data.aws_subnets.default.ids[0]
  instance_type = var.instance_type
 
  lifecycle {
    create_before_destroy = true                  #1
  }
}

Configure create_before_destroy on an AWS instance through its lifecycle block. section 2.7.2

How Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu covers it

How deep it goes
Explains replacement ordering, lifecycle placement, unique-identifier conflicts, and operational trade-offs while deferring advanced lifecycle options.
Examples
Uses an aws_instance resource with an AMI, subnet, instance type, and lifecycle setting enabled.
What it assumes
Assumes familiarity with Terraform resources and introduces lifecycle blocks as containers for lifecycle arguments.
What you can do after
Operate/configure it via Terraform to create replacement resources before destroying existing ones.
How it connects
Connects lifecycle rules with resource replacement, high availability, and unique identifiers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu. The section links point to the parts of the book it draws on.