Format Lifecycle and Meta-Argument Blocks
Format lifecycle blocks including create_before_destroy, prevent_destroy, ignore_changes, and replace_triggered_by with proper indentation and alignment.
Resources
Detailed Explanation
Formatting Lifecycle Blocks
Lifecycle meta-arguments control how Terraform creates, updates, and destroys resources. They are placed inside the resource block and require careful formatting because they affect critical infrastructure behavior.
Lifecycle Block Examples
resource "aws_instance" "critical" {
ami = var.ami_id
instance_type = var.instance_type
lifecycle {
prevent_destroy = true
}
tags = {
Name = "critical-server"
}
}
resource "aws_launch_template" "web" {
name_prefix = "web-"
image_id = data.aws_ami.ubuntu.id
instance_type = var.instance_type
lifecycle {
create_before_destroy = true
ignore_changes = [
image_id,
tags,
]
}
tags = {
Name = "web-launch-template"
}
}
resource "aws_ecs_service" "app" {
name = "app-service"
cluster = aws_ecs_cluster.main.id
task_definition = aws_ecs_task_definition.app.arn
desired_count = var.app_count
lifecycle {
ignore_changes = [desired_count]
replace_triggered_by = [
aws_ecs_task_definition.app,
]
}
}
Formatting Details
- Single-line vs multi-line: Single-value lifecycle rules (
prevent_destroy = true) stay on one line - List attributes:
ignore_changeswith multiple values uses a multi-line list with trailing commas - Single-item lists:
ignore_changes = [desired_count]can stay on one line if there is only one item - Block placement: The
lifecycleblock is typically placed after resource attributes but beforetags - Separation: A blank line before
lifecyclevisually separates it from regular attributes
Meta-Argument Ordering Convention
A common ordering convention that the formatter maintains:
countorfor_each(first)- Regular attributes
- Nested blocks (
connection,provisioner) lifecycleblockdepends_ontags(last)
Use Case
Managing critical infrastructure resources that need protection against accidental deletion, or resources that require zero-downtime updates through create-before-destroy patterns.