DEV Community

Krzysztof Kopieczek
Krzysztof Kopieczek

Posted on

terraform apply in Azure DevOps fails with "resource with the ID already exists"

Recently I was developing a simple Terraform pipeline in Azure DevOps. Everything seemed intuitive and easy - install, init, plan, apply. Clear steps and UI forms for every setting.
terraform init settings in the Azure DevOps Pipeline

Everything was configured properly. Code was working fine from my local machine, but in Azure DevOps, pipeline run successfully only for the first time. Every next attempt resulted in the following error:
Error: The process 'C:\hostedtoolcache\windows\terraform\1.0.8\x64\terraform.exe' failed with exit code 1

And details from the log:
Error: [0m[0m[1mA resource with the ID "/subscriptions/45197771-2d3e-4685-aaef-e96f62dd80b4/resourceGroups/tfexample-sample-rg" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_resource_group" for more information.[0m

The problem was in my code

provider "azurerm" {
  subscription_id = "45197771-2d3e-4685-aaef-e96f62dd80b4"
  features {}
}
Enter fullscreen mode Exit fullscreen mode

It was missing the backend part! Code worked from my local machine, because terraform saved the state in local terraform.tfstate file (default terraform behavior), but in Azure DevOps the settings provided in the UI was ignored with no clear error message. terraform apply couldn't find the state file, so was creating every resource from scratch each time.

The solution

I fixed the code by adding empty properties. That was enough to have the pipeline working correctly. Note that no values are required...

provider "azurerm" {
  subscription_id = "45197771-2d3e-4685-aaef-e96f62dd80b4"
  features {}
}

terraform {
  backend "azurerm" {
    resource_group_name = ""
    storage_account_name = "" 
    container_name       = "" 
    key                  = ""  
  }
}
Enter fullscreen mode Exit fullscreen mode

Please leave some comment if this helped.

Discussion (0)