Deploy Vms on random Datastores and Hosts from a list based on a vm name list

Hi all,

I’m struggling to find out the correct way to deploy new vms on vSphere.

I’ve defined in the list of Datastore, Host and VM name :

variable "vm_names" {
  type    = list(string)
  default = ["vm1", "vm2", "vm3", "vm4", "vm5"]  # Liste de VMs

variable "datastores" {
  type    = list(string)
  default = ["datastore1", "datastore2"]  # Liste de datastores existants

variable "hosts" {
  type    = list(string)
  default = ["host1", "host2", "host3"]  # Liste d'hôtes existants

My issue is that i’m unable to loop on the lenght of var.vm_names and randomnise the selection of datastore and host of each vm because i’ve more VM than I have Datastores and Hosts

Any idea on the way to do that ?

You said “randomize” but I wonder if in practice it’s okay for the result to be deterministic but somewhat evenly spread.

If so, you can use the element function to fetch an element using that function’s “wrap around” behavior, where indices greater than those directly in the list will be taken modulo the list length instead of returning an error:

element(var.datastores, index)

(where “index” is whatever expression returns the current index of var.vm_names.)


Thanks for reply

I’ve finally find out the solution
However we can’t do that for host, but no problem because host selection is automatic.

Here is what i’ve did :

data "vsphere_datastore" "ds" {
    datacenter_id =
    count = length(var.vsphere_datastores)
    name = var.vsphere_datastores[count.index]

  resource "random_shuffle" "ds" {
    input = data.vsphere_datastore.ds.*.id
    result_count = length(var.vm_names)
#Set VM parameteres
  resource "vsphere_virtual_machine" "Test" {
    count      = length(var.vm_names)
    name = var.vm_names[count.index]
    num_cpus = 2
    memory   = 4096
    guest_id = "ubuntu64Guest"
    resource_pool_id = data.vsphere_compute_cluster.cluster.resource_pool_id
    datastore_id     = random_shuffle.ds.result[count.index]

So it only randomise the datastore selection from my list