how/resources
create_before_destroy for zero-downtime, prevent_destroy for the critical stuff, ignore_changes for drift, replace_triggered_by for cascading rebuilds. What each one does in practice.
The lifecycle block inside resource is a meta-block. It does
not describe what the resource does in the cloud. It describes how
Terraform should treat that resource: in what order to create and
destroy it, whether to allow changes, what to recreate when
dependencies change.
Four arguments, each for its own scenario. Press ▶ and we will walk
through them and see what changes in the behavior of apply and
destroy.
Without a lifecycle block Terraform behaves predictably: if an
attribute that requires replace (force-new) changes, it first
destroys the old instance, then creates the new one.
Between those two moments the resource does not exist. For an EC2 instance behind a load balancer that is a one-second hiccup. For a database it is a loss of connections and cache. For a unique IP it is a window with no service.
Next: four ways to influence this behavior.
recap
Quick "when to use what" guide:
aws_security_group with
the same name).apply if it
tries to delete the resource. To actually tear it down, you first
remove the flag by hand and run a new apply, and only then
destroy.desired_capacity, the cloud sets
its own timestamp tags, someone bolts on tags with another tool.
It is a list of field paths where drift is allowed. Do not use it
as a "temporary crutch": you will forget, and the field will
quietly fall behind.aws_launch_template changes, and you need every aws_instance
that uses it to restart too (otherwise they keep running the old
version).There is one pitfall they all share: lifecycle cannot be set
through a variable. All four fields take only literals. So
create_before_destroy = var.zero_downtime will not work. This is a
design decision by HashiCorp, because the dependency graph is built
before evaluation.
Next: tf-variable-precedence on where Terraform gets variable values from.