Loading a CSV file into terraform

2 min read

Sometimes if you have some externally managed data it can come handy to be able to import it into terraform as a CSV file instead of having to manually enter all the date. To do so we can use the csvdecode() function

To be able to load a CSV file we will need to first load the file using the file() function and then decode it using the csvdecode() function as follows:

locals {
  instances = csvdecode(file("demo.csv"))

Assuming that the CSV file contains the following data:


It will create the following data structure:

    "VM_Name" = "evl2400123"
    "vCPU"    = "4"
    "RAM_MB"  = "16384"
    "VM_Name" = "evl2400456"
    "vCPU"    = "8"
    "RAM_MB"  = "49152"

Once we have the data loaded, we can use for_each to iterate over the different objects. We just need to pick a unique value to create the set. On the example we can use the virtual machine name:

{ for inst in local.instances : inst.VM_Name => inst }

Finally we can iterate as follows:

resource "vsphere_virtual_machine" "vm" {
  for_each = { for inst in local.instances : inst.VM_Name => inst }

  name     = each.value.VM_Name

  num_cpus = each.value.vCPU
  memory   = each.value.RAM_MB

Posted on 10/08/2021