Vsphere Virtual Machines generating same IP while provisioning through terraform count metadata

568 Views Asked by At

I want to provision multiple virtual machines in Vsphere through terraform. I am using count metadata for provisioning parallel VM, Sometimes multiple VMs get the same IP addresses. I tried multiple ways to handle it, but no luck. Please assist me to understand how to handle this scenario. I don't want to use static IPs. I am using DHCP.

When I create multiple VMs sequentially, VMs get the proper IP address, but when I tried to create using count meta-data (trying to provision multiple VMs parallel) that time it failed.

resource "vsphere_virtual_machine" "vm" {
   count = "3"
   name = "${var.vm_name}-${count.index+1}"
   resource_pool_id = data.vsphere_compute_cluster.cluster.resource_pool_id
   datastore_id     = data.vsphere_datastore.datastore.id
   folder = "VirtualMachines"
   guest_id = data.vsphere_virtual_machine.template.guest_id
   scsi_type = data.vsphere_virtual_machine.template.scsi_type

   wait_for_guest_net_timeout = 0
   
   num_cpus             = var.cpu
   num_cores_per_socket = var.cores-per-socket
   memory               = var.ram

   network_interface {
    network_id   = data.vsphere_network.network.id
    adapter_type = data.vsphere_virtual_machine.template.network_interface_types[0]
   }

   
   disk {
    label            = "${var.vm_name}-${count.index+1}-disk"
    thin_provisioned = data.vsphere_virtual_machine.template.disks.0.thin_provisioned
   # eagerly_scrub    = data.vsphere_virtual_machine.template.disks.0.eagerly_scrub
    size             = var.disksize == "" ? data.vsphere_virtual_machine.template.disks.0.size : var.disksize
   }

   clone {
      template_uuid = data.vsphere_virtual_machine.template.id 
   }
   wait_for_guest_ip_timeout = 3
} 
1

There are 1 best solutions below

0
Marko E On

The documentation says the following [1] (search for DHCP in that section):

To use DHCP, declare an empty network_interface block for each interface.

So in your case, that would mean changing the network_interface block to:

resource "vsphere_virtual_machine" "vm" {
   ...

   network_interface {}
   ...
} 

Also, you are using a combination of wait_for_guest_net_timeout and wait_for_guest_ip_timeout. The documentation says that for the newer versions of VMware Tools you need only the former. Be careful about setting that timeout as if set to less than 1 the waiter is disabled [2].


[1] https://registry.terraform.io/providers/hashicorp/vsphere/latest/docs/resources/virtual_machine#virtual-machine-customizations

[2] https://registry.terraform.io/providers/hashicorp/vsphere/latest/docs/resources/virtual_machine#wait_for_guest_net_timeout