Ignore If resource Exists

I’m testing out a large deployment of vSphere servers that we can deploy and destroy as needed. To get the information for these server we import values from a CSV file as below:

locals {
  win_server_defaults = csvdecode(file("${path.module}/win_servers.csv"))
  lin_server_defaults = csvdecode(file("${path.module}/lin_servers.csv"))
}

For example I have a column in in the CSV file which contains the value for the servers Folder location. Now in some instances this same folder will be duplicated in the CSV file.

What I’m trying to do is have Terraform say “Oh that folder already exists”, let me use that instead of trying to recreate it and getting a failure.

Here is the folder resource for example:

resource "vsphere_folder" "win_folder" {
  for_each = { for inst in local.win_server_defaults : inst.server_id => inst }
  path          = each.value.folder
  type          = "vm"
  datacenter_id = "${data.vsphere_datacenter.dc.id}"
}

Any Ideas?

Hi @rcoughtrey!

Terraform’s language does not include features for this sort of dynamic operation because the intent is that your configuration is a description of the intended result, not a description of how to achieve that result. Terraform expects that it is either managing an object or it isn’t; conditionally owning an object is not part of its model.

To think about why, consider that once you have applied that hypothetical configuration once then all of the folders would exist, and thus the next run of Terraform would be forced to conclude that it’s not supposed to manage any of them anymore, and so the system would converge on a state where Terraform is managing nothing.

This leaves you with a couple different alternative options:

  • Explicitly import the existing folders into Terraform’s care using terraform import. I’m not sure if vsphere_folder in particular supports this, but if it does you should be able to find some information about how to use it in the documentation for that resource type. In this case you’d import into a specific named instance of the resource to create the right correlation: 'vsphere_folder.win_folder["the server id"]' . Once you’ve done that, Terraform will see that these items already exist and that Terraform manages them and so subsequent changes to the configuration will be applied to them by Terraform.
  • Add a new column to your CSV file to indicate explicitly whether a particular entry is to be managed by Terraform or not, and then filter out the ones not managed by Terraform using an if clause on your for expression.

Which of these is most appropriate depends on whether your end-goal is for all of these servers to be managed by Terraform (use import) or whether Terraform will always only be managing a subset of them (use the conditional flag).