azureterraformterraform-provider-azureazure-rm

Terraform on Azure: create resource if doesn't exists and don't rename existing one


Step 0: I have a terraform script that creates resource groups from external parameters.

resource "azurerm_resource_group" "example" {
  name     = var.name
  location = "Your_Location"
}

Step 1: I define var.name = 'ABC1' so a resource group named ABC1 is created with success.

Step 2: I want to use the same script to create a resource group named ABC2 so I tried to set var.name = 'ABC2' and apply it.

But the result was that Terraform noticed that the name was changed so it deleted the ABC1 resource group and created ABC2 instead.

I'm using terraform from azure pipelines via TerraformTaskV4@4 task (init -> plan -> apply)

Is there any way to instruct terraform not to change the name of the resource but to create a new one, if the name does not exist?


Solution

  • I write here for history. I managed to do this by having .tfstate files. So when I populate the var.name variable, I also define a

    state-${{ parameters.name }}.tfstate
    

    in the hosting azure pipeline. And because of this, terraform doesn't care about what is already created with a different var.name variable and if I reuse the same value it manages to link to previously created resources.