Terraform parallel VM creation

terraform

I'm trying to do a very basic task on Terraform v0.10.7.

I have up to 100 VM to be povisionned using terraform + vSphere provisionner and I want to be able to launch several resource creations in the same time and not one after the other. For the moment the second VM is created only if the previous one is finished.

I've tried to read the doc but I didn't found any answer, could somebody help me ?

variable "user" {}
variable "password" {}
variable "vsphere_server" {}


provider "vsphere" {

 user           = "${var.user}"

 password       = "${var.password}"

 vsphere_server = "${var.vsphere_server}"

 allow_unverified_ssl = "true"

}

resource "vsphere_virtual_machine" "dum03" {
  name          = "dum03"
  hostname      = "dumHN"
  folder        = "Ansible VM"
  vcpu          = 2
  memory        = 4096
  domain        = "MYDOMAIN"
  datacenter    = "myDatacenter"
  cluster       = "NET-TEST"

  network_interface {
    label              = "NET-TEST"
    ipv4_address       = "10.20.30.40"
    ipv4_prefix_length = "24"
    ipv4_gateway       = "10.20.30.254"
  }
  disk {
    datastore = "datastore"
    template  = "mytemplate"
  }
}

resource "vsphere_virtual_machine" "dum04" {
  name          = "dum4"
  hostname      = "dumHN2"
  folder        = "Ansible VM"
  vcpu          = 2
  memory        = 4096
  domain        = "MYDOMAIN"
  datacenter    = "myDatacenter"
  cluster       = "test"

  network_interface {
    label              = "NET-TEST"
    ipv4_address       = "15.25.35.45"
    ipv4_prefix_length = "24"
    ipv4_gateway       = "10.20.30.254"
  }
  disk {
    datastore = "mydatastore"
    template  = "mytemplate"
  }
}

Best Answer

You need to start all your VMs within one vsphere_virtual_machine resource using count statement. Count starts from 0.

It should be like:

variable "vm_count" = 2

resource "vsphere_virtual_machine" "dum" {
  name          = "dum${format("%02d", count.index+3)}"
  hostname      = "dumHN${count.index+1}"
  count         = "${var.vm_count}"
  folder        = "Ansible VM"
  vcpu          = 2
  memory        = 4096
  domain        = "MYDOMAIN"
  datacenter    = "myDatacenter"
  cluster       = "NET-TEST"

  network_interface {
    label              = "NET-TEST"
    ipv4_address       = "10.20.30.${40 + count.index * 5)}"
    ipv4_prefix_length = "24"
    ipv4_gateway       = "10.20.30.254"
  }
  disk {
    datastore = "datastore"
    template  = "mytemplate"
  }
}
Related Topic