0
0
Terraformcloud~15 mins

Create_before_destroy lifecycle rule in Terraform - Deep Dive

Choose your learning style9 modes available
Overview - Create_before_destroy lifecycle rule
What is it?
The create_before_destroy lifecycle rule in Terraform tells the system to make a new resource first before removing the old one. This helps avoid downtime by ensuring the new resource is ready before the old one goes away. It is used when replacing resources that cannot be offline without causing problems. This rule changes the order Terraform follows when updating infrastructure.
Why it matters
Without create_before_destroy, Terraform deletes the old resource before creating the new one, which can cause service interruptions or data loss. For example, if a server or database is destroyed before the new one is ready, users may experience downtime. This rule ensures smooth transitions and continuous availability, which is critical for real-world systems that must stay online.
Where it fits
Before learning this, you should understand basic Terraform resource creation and destruction. After this, you can learn about other lifecycle rules like prevent_destroy and ignore_changes, and how to manage complex infrastructure updates safely.
Mental Model
Core Idea
Create_before_destroy means always build the new thing first, then remove the old one, so nothing breaks during changes.
Think of it like...
It's like moving houses by first setting up your new home fully before leaving the old one, so you never have to live on the street.
┌───────────────┐       ┌───────────────┐
│ Old Resource  │──────▶│ New Resource  │
│ (In Use)      │       │ (Created)     │
└──────┬────────┘       └──────┬────────┘
       │                       │
       │ Destroy old only after│
       │ new is ready         │
       ▼                       ▼
  ┌───────────────┐       ┌───────────────┐
  │ Old Resource  │       │ New Resource  │
  │ (Destroyed)   │       │ (In Use)      │
  └───────────────┘       └───────────────┘
Build-Up - 7 Steps
1
FoundationTerraform resource lifecycle basics
🤔
Concept: Terraform manages resources by creating, updating, or destroying them based on configuration changes.
When you run Terraform apply, it compares your desired state with the current state. If a resource needs to change, Terraform decides whether to update it in place or replace it by destroying and recreating it.
Result
Terraform creates new resources, updates existing ones, or destroys old ones to match your configuration.
Understanding how Terraform manages resource lifecycle is key to controlling infrastructure changes safely.
2
FoundationDefault resource replacement behavior
🤔
Concept: By default, Terraform destroys a resource before creating its replacement when changes require replacement.
If a resource attribute change forces replacement, Terraform first destroys the old resource, then creates the new one. This can cause downtime if the resource is critical.
Result
Resource is unavailable between destroy and create steps.
Knowing the default destroy-then-create order helps explain why some updates cause downtime.
3
IntermediateIntroducing create_before_destroy rule
🤔Before reading on: do you think Terraform creates the new resource before destroying the old one by default? Commit to yes or no.
Concept: The create_before_destroy lifecycle rule changes the order to create the new resource first, then destroy the old one.
You add lifecycle { create_before_destroy = true } inside a resource block. This tells Terraform to keep the old resource until the new one is ready, avoiding downtime.
Result
Terraform creates the new resource first, then destroys the old one after the new is ready.
Understanding this rule helps prevent service interruptions during resource replacements.
4
IntermediateApplying create_before_destroy in Terraform code
🤔Before reading on: do you think create_before_destroy works with all resource types or only some? Commit to your answer.
Concept: Not all resources support create_before_destroy; it depends on the provider and resource type.
Example: resource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" lifecycle { create_before_destroy = true } } This tells Terraform to create the new instance before destroying the old one.
Result
Terraform applies changes with zero downtime for supported resources.
Knowing resource support limits helps avoid unexpected errors during apply.
5
IntermediateHandling dependencies with create_before_destroy
🤔Before reading on: do you think create_before_destroy affects resource dependencies automatically? Commit to yes or no.
Concept: Terraform respects dependencies and will create dependent resources in the correct order even with create_before_destroy.
If resource A depends on resource B, Terraform creates the new B first, then new A, then destroys old A and B. This ensures consistency.
Result
Dependencies remain intact and consistent during replacements.
Understanding dependency handling prevents broken infrastructure during updates.
6
AdvancedLimitations and edge cases of create_before_destroy
🤔Before reading on: do you think create_before_destroy can cause resource conflicts or duplicates? Commit to yes or no.
Concept: Using create_before_destroy can cause conflicts if the provider or resource does not allow duplicates or if naming conflicts occur.
For example, some cloud resources require unique names. Creating a new resource before destroying the old one may fail if the name is already taken. You must plan naming or use other lifecycle rules.
Result
Potential apply failures or resource conflicts if not handled properly.
Knowing these limits helps design safer infrastructure updates.
7
ExpertInternal Terraform process with create_before_destroy
🤔Before reading on: do you think Terraform creates and destroys resources in parallel or sequentially with create_before_destroy? Commit to your answer.
Concept: Terraform plans a replacement by creating a new resource, waits for it to be ready, then destroys the old one, respecting dependencies and state consistency.
Terraform's engine tracks resource states and uses a two-step replacement: first create new, then destroy old. It updates the state file only after the new resource is confirmed ready, ensuring no downtime or state mismatch.
Result
Safe, ordered resource replacement with consistent state.
Understanding Terraform's internal orchestration clarifies why create_before_destroy avoids downtime and how state consistency is maintained.
Under the Hood
Terraform's engine plans resource changes by comparing desired and current states. When create_before_destroy is set, it marks the resource for replacement but changes the order: it first creates the new resource, waits for it to be fully provisioned and healthy, then destroys the old resource. This requires Terraform to track both resources simultaneously in its state until the old one is removed. The state file is updated only after the new resource is ready, ensuring no downtime or inconsistent state.
Why designed this way?
Originally, Terraform destroyed resources before creating replacements to avoid conflicts and simplify state management. However, this caused downtime for critical resources. The create_before_destroy rule was introduced to support zero-downtime updates by reversing the order. This design balances safety and availability but requires providers and resources to support simultaneous existence of old and new resources.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Desired State │──────▶│ Plan Replace  │──────▶│ Apply Changes │
└──────┬────────┘       └──────┬────────┘       └──────┬────────┘
       │                       │                       │
       │                       │                       │
       ▼                       ▼                       ▼
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Old Resource  │       │ New Resource  │       │ Old Resource  │
│ (In State)    │       │ (Created)     │       │ (Destroyed)   │
└───────────────┘       └───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does create_before_destroy guarantee zero downtime for all resources? Commit to yes or no.
Common Belief:Create_before_destroy always prevents downtime no matter the resource.
Tap to reveal reality
Reality:It only prevents downtime if the resource and provider support simultaneous existence and creation before destruction. Some resources or providers do not support this.
Why it matters:Assuming zero downtime always can lead to unexpected outages if the resource cannot exist twice or if naming conflicts occur.
Quick: Does create_before_destroy mean Terraform creates both resources permanently? Commit to yes or no.
Common Belief:Terraform keeps both old and new resources forever when using create_before_destroy.
Tap to reveal reality
Reality:Terraform only keeps both temporarily during replacement. After the new resource is ready, the old one is destroyed and removed from state.
Why it matters:Misunderstanding this can cause confusion about resource counts and billing during apply.
Quick: Does create_before_destroy work automatically without configuration? Commit to yes or no.
Common Belief:Terraform always creates new resources before destroying old ones by default.
Tap to reveal reality
Reality:By default, Terraform destroys first then creates. You must explicitly set create_before_destroy in lifecycle to change this.
Why it matters:Assuming default behavior is create_before_destroy can cause unexpected downtime.
Quick: Can create_before_destroy cause naming conflicts? Commit to yes or no.
Common Belief:No, create_before_destroy never causes naming conflicts because Terraform manages names automatically.
Tap to reveal reality
Reality:Yes, if the resource requires unique names, creating a new resource before destroying the old one can cause conflicts unless names are changed or managed carefully.
Why it matters:Ignoring this can cause apply failures and block deployments.
Expert Zone
1
Some providers require explicit support for create_before_destroy; otherwise, Terraform will error or fallback to destroy-before-create.
2
Using create_before_destroy can increase resource costs temporarily because both old and new resources exist simultaneously during replacement.
3
Complex dependencies can cause Terraform to reorder resource replacements in unexpected ways when create_before_destroy is used, requiring careful planning.
When NOT to use
Avoid create_before_destroy when the resource cannot exist twice simultaneously, such as unique IP addresses or singleton services. Instead, use blue-green deployments or manual migration strategies.
Production Patterns
In production, create_before_destroy is used for critical resources like load balancers, databases, or servers to ensure zero downtime. It is combined with careful naming, dependency management, and sometimes manual approval steps to avoid conflicts.
Connections
Blue-Green Deployment
Builds-on
Create_before_destroy is an automated way to implement blue-green deployment patterns by creating new resources before removing old ones, ensuring continuous availability.
State Management in Infrastructure as Code
Builds-on
Understanding how Terraform tracks resource states is essential to grasp why create_before_destroy updates state only after new resource readiness, preventing inconsistencies.
Transactional Systems in Databases
Analogy in different domain
Like transactions that commit only after all steps succeed, create_before_destroy ensures infrastructure changes apply atomically by creating new resources before destroying old ones.
Common Pitfalls
#1Causing downtime by not using create_before_destroy for critical resources.
Wrong approach:resource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" # No lifecycle block }
Correct approach:resource "aws_instance" "example" { ami = "ami-123456" instance_type = "t2.micro" lifecycle { create_before_destroy = true } }
Root cause:Not understanding the default destroy-before-create behavior causes unintended downtime.
#2Applying create_before_destroy on resources that require unique names without changing names.
Wrong approach:resource "aws_s3_bucket" "example" { bucket = "my-unique-bucket" lifecycle { create_before_destroy = true } }
Correct approach:resource "aws_s3_bucket" "example" { bucket = "my-unique-bucket-${random_id.suffix.hex}" lifecycle { create_before_destroy = true } } resource "random_id" "suffix" { byte_length = 4 }
Root cause:Ignoring resource uniqueness constraints causes conflicts during simultaneous existence.
#3Assuming create_before_destroy works without provider support.
Wrong approach:resource "some_provider_resource" "example" { # ... lifecycle { create_before_destroy = true } }
Correct approach:Check provider documentation and avoid create_before_destroy if unsupported, or use alternative update strategies.
Root cause:Not verifying provider capabilities leads to apply errors.
Key Takeaways
Terraform's create_before_destroy lifecycle rule changes resource replacement order to create new resources before destroying old ones, reducing downtime.
This rule is essential for critical infrastructure that must remain available during updates, like servers or databases.
Not all resources or providers support create_before_destroy, so understanding limitations and naming constraints is crucial.
Terraform manages state carefully during create_before_destroy to ensure consistency and safe transitions.
Using create_before_destroy effectively requires planning dependencies, resource uniqueness, and provider capabilities.