Prevent Terraform from Destroying Resources in Azure

In this blog post, I will show you how to prevent Terraform from destroying resources in Azure with the destroy command.


By default, if you run on any Terraform configuration the terraform destroy command all the resources in the configuration will get deleted. This is not a bad idea if you need to delete all the resources, but mistakes happen.

For that reason, Terraform gives us the option to change this default behaviour and use the lifecycle command and prevent Terraform from deleting resources.


The following code shows how you can prevent it from happening. In the following example, I am creating a resource group. To prevent deletion, I am adding the lifecycle code, as shown below.

resource "azurerm_resource_group" "rg" {
  name     = "TRFDemo"
  location = "westus2"

   lifecycle {
    prevent_destroy = true