Terraform Lifecycle: create_before_destroy vs prevent_destroy
Compare Terraform replacement ordering and destroy protection with a local terraform_data lab, JSON plan actions and verified configuration-removal behavior.
create_before_destroy changes the order of a replacement: Terraform proposes creating the new object before deleting the old one. prevent_destroy rejects a plan that would destroy a protected object while the rule remains in its resource configuration. They solve different problems, and neither is an availability guarantee or an external deletion lock. This guide demonstrates the difference with real Terraform CLI execution against disposable local state, including the easily missed case where removing the resource block removes its protection.
Decide whether replacement is allowed before choosing its order
An intended configuration change can produce an in-place update, a replacement or an error. Before adding a lifecycle rule, establish which behavior the resource actually proposes. Changing an ordinary editable setting and changing an immutable setting are different operations, even if both appear as a small text edit in a pull request.
For a replaceable stateless worker, the operational question may be whether the new worker can be created while the old worker remains. For a stateful record, the first question may instead be whether replacement is acceptable at all. Choosing create-first ordering does not answer the second question. A plan that creates and then deletes still contains a deletion.
The exercise uses terraform_data so those decisions can be observed without cloud credentials, a provider download or billable infrastructure. Its input field gives us an editable value, while changing triggers_replace deliberately requests replacement. These invented values represent a lifecycle experiment, not an application deployment or a database migration.
The smallest local resource that separates update from replacement
The baseline resource below stores first as its input and v1 as its replacement trigger. After its initial local apply, an unchanged plan is a no-op. Changing input to edited produces an update. Keeping input unchanged and changing triggers_replace to v2 produces a replacement.
This controlled distinction avoids relying on an assumed cloud provider schema. A real resource may require replacement for different attributes, and that decision can change with provider versions. Read its provider documentation and inspect the plan for the actual locked dependency versions.
The following HCL is the baseline generated by the complete lab. The lab pins Terraform 1.13.5 for reproducibility; this is the tested version, not a claim that it is the newest release. Use a separate disposable directory for manual exploration. Do not transplant the lab’s automatic initial apply into an existing infrastructure repository.
terraform { required_version = "= 1.13.5" }
resource "terraform_data" "sample" {
input = "first"
triggers_replace = "v1"
}Read replacement ordering from the JSON action array
For the default-policy fixture, the saved plan reports ["delete", "create"] when triggers_replace changes. With create_before_destroy = true inside lifecycle, the same change reports ["create", "delete"]. The order of the two entries is the useful evidence here; both arrays describe a replacement.
The lab selects terraform_data.sample by its full address before checking change.actions. It does not assume the resource is the first entry in resource_changes. In a larger plan, inspect every relevant address and its dependencies rather than turning one matched array into blanket approval.
The plan command runs with -detailed-exitcode. Zero means a successful plan with no changes; two means a successful plan with proposed changes; one means an error. A lifecycle rejection is therefore not another ordinary difference to apply. The harness only reads a saved plan after a successful planning result.
Observe what prevent_destroy permits and blocks
The protected fixture still permits an in-place input edit. Its replacement-trigger edit fails with a prevent_destroy diagnostic, because replacement includes deleting the existing instance. A destroy-mode plan also fails while that resource block retains the rule.
The both fixture enables create_before_destroy and prevent_destroy together. It still rejects replacement. Creating first does not make a later deletion compatible with the protection rule. This is a useful regression case when someone assumes the two settings combine into a safe automatic migration.
Treat the rejection as information about the proposed operation. Identify the replacement trigger, the data or identity being replaced, and the intended migration path. Removing protection to make a pipeline pass changes the policy; it does not explain or reduce the consequences of the replacement.
| Fixture | input edit | triggers_replace edit | Destroy-mode plan |
|---|---|---|---|
| No lifecycle rule | update | delete, create | Proposed deletion |
| create_before_destroy | update | create, delete | Proposed deletion |
| prevent_destroy | update | Error | Error |
| Both rules | update | Error | Error |
Removing the resource block also removes its guard
After creating each baseline, the lab replaces main.tf with only its terraform block. Terraform still has the resource in local state, but the configuration no longer contains the resource or its prevent_destroy setting. All four fixtures then produce a delete action. The removal plan is inspected and never applied.
This is why prevent_destroy should not be described as a permanent lock attached to the remote object. It cannot protect an object from an unrelated administrator or another tool either. If the intended operation is to stop managing an object while preserving it, use the documented state-removal workflow appropriate to your Terraform version and review that change separately.
In code review, look for deleted resource blocks as well as edits inside surviving blocks. A policy that searches only for prevent_destroy = false misses the case where the protected block disappears entirely. The local removal fixture provides a compact test of that review assumption.
Run the complete four-policy experiment
Install the official Terraform 1.13.5 CLI for your platform and Python 3.12 or later, then save this program as lifecycle_lab.py. Run python3 lifecycle_lab.py if terraform is on PATH, or set TERRAFORM_BIN to the absolute path of that binary. The exact listing was executed with Terraform 1.13.5 on Linux amd64 and Python 3.12.14.
The program creates temporary directories with local state and no backend block. Its only apply creates an invented terraform_data record. It does not execute provisioners or call a cloud API. Updates, replacements, destroy operations and configuration removals are planned only. Temporary files are removed when the program exits.
Expected output ends with PASS: 36 checks across 46 Terraform CLI commands. Each policy gets its own baseline state, so a successful update or replacement in one fixture cannot alter a later comparison. The script restores the original v1 configuration before checking destroy mode.
An init or validate failure stops the experiment. A version-constraint error usually means a different binary was selected; check TERRAFORM_BIN and terraform version. Do not delete the version constraint merely to reproduce the published result with an unreported version.
"""Disposable local-state lab: Terraform 1.13.5; Python 3.12+."""
import json
import os
from pathlib import Path
import subprocess
import tempfile
TF = os.environ.get('TERRAFORM_BIN', 'terraform')
ENV = {**os.environ, 'CHECKPOINT_DISABLE': '1', 'TF_IN_AUTOMATION': '1'}
# Do not inherit a real environment's backend, workspace or CLI arguments.
for key in list(ENV):
if key.startswith('TF_CLI_ARGS') or key in ('TF_WORKSPACE', 'TF_DATA_DIR'):
ENV.pop(key)
checks = 0
commands = 0
def check(condition, label):
global checks
checks += 1
if not condition:
raise AssertionError(label)
def run(folder, *args):
global commands
commands += 1
return subprocess.run([TF, *args], cwd=folder, env=ENV,
text=True, capture_output=True, timeout=45)
def success(folder, *args):
result = run(folder, *args)
if result.returncode != 0:
raise RuntimeError(result.stdout + result.stderr)
return result
HEADER = 'terraform { required_version = "= 1.13.5" }\n'
def write_config(folder, policy, note='first', generation='v1'):
lifecycle = ''
if policy:
lifecycle = ' lifecycle {\n' + ''.join(
f' {name} = true\n' for name in policy) + ' }\n'
(folder / 'main.tf').write_text(HEADER +
'resource "terraform_data" "sample" {\n' +
f' input = {json.dumps(note)}\n' +
f' triggers_replace = {json.dumps(generation)}\n' +
lifecycle + '}\n')
def planned_actions(folder):
result = run(folder, 'plan', '-input=false', '-no-color',
'-detailed-exitcode', '-out=lab.tfplan')
if result.returncode not in (0, 2):
return result.returncode, None, result.stdout + result.stderr
data = json.loads(success(folder, 'show', '-json', 'lab.tfplan').stdout)
changes = [r for r in data.get('resource_changes', [])
if r['address'] == 'terraform_data.sample']
check(len(changes) == 1, 'one addressed resource change')
return result.returncode, changes[0]['change']['actions'], ''
def main():
policies = {
'default': (),
'create-first': ('create_before_destroy',),
'protected': ('prevent_destroy',),
'both': ('create_before_destroy', 'prevent_destroy'),
}
with tempfile.TemporaryDirectory(prefix='tf-lifecycle-lab-') as temp:
for label, policy in policies.items():
folder = Path(temp) / label
folder.mkdir()
write_config(folder, policy)
success(folder, 'init', '-input=false', '-no-color')
success(folder, 'validate', '-no-color')
# Applies only the invented terraform_data record to local state.
success(folder, 'apply', '-input=false', '-no-color', '-auto-approve')
code, actions, _ = planned_actions(folder)
check(code == 0 and actions == ['no-op'], label + ': baseline')
write_config(folder, policy, note='edited')
code, actions, _ = planned_actions(folder)
check(code == 2 and actions == ['update'], label + ': in-place input edit')
write_config(folder, policy, generation='v2')
code, actions, error = planned_actions(folder)
protected = 'prevent_destroy' in policy
if protected:
check(code == 1 and 'prevent_destroy' in error,
label + ': replacement blocked')
else:
expected = ['create', 'delete'] if policy else ['delete', 'create']
check(code == 2 and actions == expected, label + ': replacement order')
# Restore v1 configuration; no replacement/update plan was applied.
write_config(folder, policy)
destroy = run(folder, 'plan', '-destroy', '-input=false', '-no-color',
'-detailed-exitcode')
check(destroy.returncode == (1 if protected else 2), label + ': destroy plan')
if protected:
check('prevent_destroy' in destroy.stdout + destroy.stderr,
label + ': destroy diagnostic')
# Removing the block removes prevent_destroy from configuration too.
(folder / 'main.tf').write_text(HEADER)
code, actions, _ = planned_actions(folder)
check(code == 2 and actions == ['delete'], label + ': removed block')
print(label + ': baseline, update, replacement, destroy and removal checked')
print(f'PASS: {checks} checks across {commands} Terraform CLI commands')
if __name__ == '__main__':
main()What create-first ordering still leaves unresolved
The local resource has no naming collision, capacity quota, health check, client traffic or data synchronization. A cloud replacement can have all of those constraints. Before using create-first ordering, verify that old and new objects can coexist under the resource’s naming and uniqueness rules and that capacity is available for the overlap.
For an application service, creating the replacement object is only one event in a cutover. Define when it is ready, how traffic moves and how the old instance is drained. For stateful services, define how the new object gets correct data and how writes are handled during the transition. The action order alone supplies none of those application-specific decisions.
HashiCorp also documents propagation of create_before_destroy to dependencies and its interaction with destroy-time provisioners. The single-resource lab does not exercise either behavior. Review the dependency graph and the resource-specific teardown design before transferring this result to a multi-resource stack.
Use the experiment to ask better plan-review questions
First separate the reason for replacement from its execution order. In this lab, the reason is an intentionally changed triggers_replace value. In a production plan, examine the changed paths, provider constraints and any explicit replacement request. Adding a lifecycle rule does not make the original reason disappear.
Next, compare the desired policy with every destructive action in the plan. If replacement is forbidden, a create-then-delete array is still incompatible. If replacement is permitted, check the coexistence and cutover requirements before approving create-first ordering. Review configuration deletions independently because the protection rule may vanish with the block.
Finally, preserve the relationship between the reviewed inputs and the plan that will be applied. The harness overwrites lab.tfplan for convenience inside a throwaway experiment. A production workflow needs an exact reviewed artifact and appropriate access controls. Plan files and JSON exports can contain sensitive values; avoid treating them as public build logs.
Distinguish a useful rejection from an incomplete test
If the input edit is an update in the fixture but your cloud resource is replaced, that is not a contradiction. The resource types and schemas are different. Reproduce the change with the actual provider version and confirm which field forces replacement instead of generalizing from terraform_data.
If a protected replacement produces an error, do not inspect a stale lab.tfplan left by a previous successful plan and call it the new result. The harness returns the current diagnostic immediately on a planning error. Your automation should similarly bind the artifact to the command that successfully created it.
If removing the block yields a delete action, confirm whether deletion is actually the intended task. Preventing a Terraform-managed destroy, retiring infrastructure and relinquishing management are separate workflows. Decide which one you want before applying any plan or modifying state.
Make the intended policy explicit
The experiment verifies planning behavior for one built-in resource on one pinned CLI version. It does not apply replacements, test dependency propagation, exercise remote APIs or establish a zero-downtime procedure. Those limits are central to interpreting the result: the JSON actions demonstrate Terraform’s proposed sequence, not the readiness of a real replacement.
Use prevent_destroy when the intended policy is to reject destructive plans while the resource rule remains configured. Use create_before_destroy when replacement is permitted and the resource can support overlap. Keep the replacement reason, deletion policy and operational cutover visible as separate decisions in the review.
Your next steps
- A create-then-delete replacement still includes deletion; ordering does not override prevent_destroy.
- Test block removal as well as edits: a removed resource configuration no longer carries prevent_destroy.
- Use local plan experiments to understand CLI behavior, then verify provider constraints and application cutover separately.
Sources & official resources
Linked resources checked on 2026-11-01. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →