I have 2 terraform scripts to provision different resources in the same resource group in azure (using latest provider version 1.35, but got the same behavior with 1.28).
lets say first.tf creates resource a in resource group rg
and second.tf creates resource b in same resource group rg
resource a and b are different types.
resource a is not defined in second.tf and for whatever reason I cant define it.
I apply first.tf then I apply second.tf
when applying second.tf, it removes the resource a that first.tf created !!!
I want terraform to append to the resource group and not delete existing resources.
I have tried importing the resource group but this has the same result.
Is this expected behavior? How do I make terraform not delete existing resources?
I’m not familiar with the Azure resources, but can you not store both first.tf and second.tf in the same directory? If they were applied at the same time, might that fix your issue? Are you defining the resource group rg twice, or is it only defined in one file? Is the resource group a data source you are referencing from both files? There is a lot of unknowns in your example.
From your answer can I assume this is not expected behavior? Beyond the unknowns you’re referring to, terraform azure provider should not destroy existing resources.
Nevermind I re-read you answer and I can’t assume this.
first.tf and second.tf are stored in different directories but use the same remote backend and workspace (as far as i know this should not make a difference as long as I select the right workspace)
As far as the Resource Group goes, I’d already tried every combination of your suggestion with the same result (manually creating rg before and using data block for rg in first.tf and second.tf, creating rg only in first and using rg as data block in second, having rg resource block in both)
Also let me share the workaround I’m using right now:
I create resource a in a module which is called by both first.tf and second.tf. This way the resource is created in first.tf and not destroyed in second.tf.
Where are you defining the creation of resource group rg?
I suspect that by applying first.tf and second.tf sepparately, you are telling terraform to create a resource group with resource a but without resource b (first.tf), and then you are telling terraform to create a resource group with resource b but without resource a (second.tf), so it deletes the resources that are present and shouldn’t be, according to its plan.
If you store both files in the same directory (or merge the resources definition into one file only) and execute everything in the same round (terraform init, terraform plan -out=my.tfplan, terraform apply my.tfplan), terraform would get just one order to create a resource group with both resources.