Terraform & Azure - Terraform destroy

Amine Charot
3 min readNov 13, 2019

--

Hello, after all these news related to Microsoft and Terraform, we can say that Microsoft really loves Terraform.

Terraform may deploy your services on Azure. But unfortunately, you may not find a service in the Azure Provider.

Terraform provides the ability to deploy a resource of type ARM Template so you can bypass the service unavailability on AzureRm provider. You can do it using :

azurerm_template_deployment

Are you happy ? Nice, glad you are. Did you try Terraform destroy ?

Actually, by running Terraform destroy, it will destroy the resource deployed in Terraform state but not the resource Azure since it was deployed with an ARM Template.

Note from Terraform documentation

This contradict Terraform principles. When we run the destroy command, we must remove all the resources that we’ve created.

  • How to destroy a resource deployed with azurerm_template_deployment :

All you need is to output the resourceId from the ARM Template. Then, use the provisioner "local-exec" to remove the resource as following :

By running the Terraform destroy, the local-exec will run to remove the appropriate resource.

  • Putting all together :

Let’s try this, first of all, I will deploy a storage account using an ARM Template inside TF (I am sorry if the template sucks, but the goal is to prove that the destroy is working).

Terraform Plan says that I’m going to deploy the ARM Template :

Great, let’s apply :

No my storage has been created :

Now, if I run the Terraform destroy without the “local-exec”, nothing will happen. But using it, you can see magic :

And if I check my Azure Portal :

Magic !

Bella ciao,

--

--