# ESXi

# Render userdata template with skylab SSH key
data "template_file" "esxi_userdata" {
  template = file("${path.module}/userdata.tftpl")
  vars = {
    skylab-ssh-key = trimspace(var.skylab_ssh_public_key)
  }
}

resource "esxi_portgroup" "les-5-opdracht-3" {
  name    = "${var.prefix}-network"
  vswitch = "vSwitch0"
}


resource "esxi_guest" "les-5-opdracht-3" {
  guest_name = var.prefix
  disk_store = "datadisk1"

  memsize  = "2048"
  numvcpus = "1"
  power    = "on"

  ovf_source = "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-amd64.ova"

  network_interfaces {
    virtual_network = esxi_portgroup.les-5-opdracht-3.name
  }

  guestinfo = {
    "metadata" = base64encode(templatefile("${path.module}/metadata.yaml", {
      hostname = "${var.prefix}"
    }))
    "metadata.encoding" = "base64"
    "userdata"          = base64encode(data.template_file.esxi_userdata.rendered)
    "userdata.encoding" = "base64"
  }
}

locals {
  inventory = templatefile("${path.module}/ansible-inventory.tmpl", {
    name             = esxi_guest.les-5-opdracht-3.guest_name
    ip               = esxi_guest.les-5-opdracht-3.ip_address
    private_key_file = var.skylab_ssh_public_key
  })
}

resource "local_file" "ansible_inventory" {
  content  = local.inventory
  filename = "${path.module}/inventory.ini"
}

output "ip_addresses" {
  value = local_file.ansible_inventory.content
}
