terraform {
  required_providers {
    vsphere = {
      source  = "hashicorp/vsphere"
      version = "~> 2.8"
    }
  }
}

provider "vsphere" {
  user                 = var.vsphere_user
  password             = var.vsphere_password
  vsphere_server       = var.vsphere_server
  allow_unverified_ssl = true
}

data "vsphere_datacenter" "dc" {
  name = var.datacenter
}

data "vsphere_datastore" "ds" {
  name          = var.datastore
  datacenter_id = data.vsphere_datacenter.dc.id
}

data "vsphere_compute_cluster" "cluster" {
  name          = var.cluster
  datacenter_id = data.vsphere_datacenter.dc.id
}

data "vsphere_network" "network" {
  name          = var.network
  datacenter_id = data.vsphere_datacenter.dc.id
}

data "vsphere_virtual_machine" "web" {
  name          = var.vm_name
  datacenter_id = data.vsphere_datacenter.dc.id
}

# Lab VM create (SOAP CreateVM_Task). Use a unique name per apply.
resource "vsphere_virtual_machine" "lab" {
  count            = var.create_lab_vm ? 1 : 0
  name             = var.lab_vm_name
  resource_pool_id = data.vsphere_compute_cluster.cluster.resource_pool_id
  datastore_id     = data.vsphere_datastore.ds.id
  num_cpus         = 1
  memory           = 1024
  guest_id         = "otherGuest64"
  wait_for_guest_net_timeout = 0
  wait_for_guest_ip_timeout  = 0

  network_interface {
    network_id = data.vsphere_network.network.id
  }

  disk {
    label = "disk0"
    size  = 16
  }
}

output "vm_id" {
  value = data.vsphere_virtual_machine.web.id
}

output "lab_vm_id" {
  value = try(vsphere_virtual_machine.lab[0].id, null)
}
