Following my last blog post: API Management Terraform deployment error: The user, group or application ‘does not have secrets get permission on key vault. Last week, while developing and deploying an API Management Terraform Visual Studio solution into our development environment, we got another error:
Error: A resource with the ID “/subscriptions/<subs-id>/resourceGroups/RG-name/providers/Microsoft.ApiManagement/service/<APIM-name>/apis/<api-name>/diagnostics/applicationinsights” already exists – to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for “azurerm_api_management_api_diagnostic” for more information.
Cause
The error message you’re encountering during your Terraform deployment indicates that the resource you’re trying to create already exists in your infrastructure but isn’t recognized in Terraform’s state file. This situation typically occurs if the resource was created outside of Terraform or if the state file was modified or lost.
In my case, two of us were working on the same project without knowing. I fixed some issues on the project and successfully deployed the solution. When I realized that my team member was also working on the project, adding extra functionalities that I had asked for, I uncommit my changes, and we replicated the small fixes I had made on his side.
When he tried to deploy the solution, he got the error above.
Solution
The solution to this problem is simple, you’ll need to import the existing resource into your Terraform state file (terraform.tfstate
) so that Terraform can manage it. In this particular case, we have to run the following command:
terraform import azurerm_api_management_api_diagnostic.api_sap "/subscriptions/<subs-id>/resourceGroups/RG-name/providers/Microsoft.ApiManagement/service/<APIM-name>/apis/<api-name>/diagnostics/applicationinsights"
After we imported this resource to the Terraform state file, we were able to deploy our solution once again.
Hope you find this helpful! So, if you liked the content or found it useful and want to help me write more, you can buy (or help me buy) my son a Star Wars Lego!