Is there a way to bypass the lifecycle.prevent_destroy flag for an execution?

Within our team we use Terraform to manage our AWS resources. Recently we encountered a situation where a terraform apply would result in resources being destroyed that persist data, like our DynamoDB tables.

Obviously this happening in client-facing environments is a Bad Thing, so we added the prevent_destroy lifecycle attribute to those resources that needed to be persisted.

However, now we are faced with a situation where, in some particular cases, we want to apply configurations regardless of these flags. For instance, we have a build pipeline that creates resources, does some operations and then tears down these resources again.

Ideally we would want to provide some command-line argument to terraform that indicates it can safely ignore the prevent_destroy flag on some, or all resources. However, I’ve not been able to find anything in the documentation.

Are there ways to do this with Terraform?

Add a variable (something like “prevent_destroy” as a boolean with a default of true) and use that for the resources you want to protect. Then when you want to ignore it run terraform apply -var='prevent_destroy=false'

Unfortunately this isn’t possible, as the value of lifecycle flags cannot be a variable, but must be a literal value, as per the documentation.