25/05/2021
Terraform
Azure
import

When you work with existing resources in Azure, it will come up, that you must work with existing ressources that you must modify. For Example I got the following definition for a logicapp:

resource "azurerm_logic_app_workflow" "sendmail" {
  resource_group_name = azurerm_resource_group.rg.name
  location = "westeurope"
  name = "la-sendmail"
  depends_on = [  
    azurerm_template_deployment.officeconnection,
    azurerm_template_deployment.servicebusConnection
  ]
}

After executing terraform apply I got the following error:

A resource with the ID "/subscriptions/xxxxx/resourceGroups/RG-YYYY/providers/Microsoft.Logic/workflows/la-sendmail" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_logic_app_workflow" for more information.

# The problem

Terraform want's to check the provisioning state for this ressources. In a greenfield scenario it will create the ressource when it not exists. But in this case, it cannot create the ressource, because another resource with the same name already exits in the ressourcegroup.

So Terraform could not track the neccessary changes for the provisioninig

# The solution

To make it happen you must import the existing ressource to the state with the terraform import {name} {ID} command

You must use the ressource ID from the ressource it self. You will find it in the properties dialog of the ressource in the azure portal:

Now when we got the ID we can build our command to import the current resource to terraform state:

terraform import azurerm_logic_app_workflow.sendmail /subscriptions/12fad0e4-f22f-481b-91ca-5c9c34a969fb/resourceGroups/RG-IT2-KA-DEV/providers/Microsoft.Logic/workflows/la-sendmail

When it all was OK, you will get this receipt:

azurerm_logic_app_workflow.sendmail: Importing from ID "/subscriptions/XXXXX/resourceGroups/RG-YYY/providers/Microsoft.Logic/workflows/la-sendmail"...
azurerm_logic_app_workflow.sendmail: Import prepared!
  Prepared azurerm_logic_app_workflow for import
azurerm_logic_app_workflow.sendmail: Refreshing state... [id=/subscriptions/XXXXX/resourceGroups/RG-YYYY/providers/Microsoft.Logic/workflows/la-sendmail]

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

# Conclusion

Terraform is a nice tool to provision some resources, to work with existing ressources, you must import the current state into the terraform state. After that you can use it like a normal provisioning.

👋 Hi ich bin's, Sascha