terraform {
  required_providers {
    ovh = {
      source = "ovh/ovh"
      version = "2.3.0"
    }
  }
}

provider "ovh" {
  endpoint      = "ovh-eu"
}

variable project_id {
  type = string
  default = "c67c62fb7a574a88ba4caaca53561c8a"
}

variable region {
  type = string
  default = "SBG5"
}

// The flavor can be selected directly, name_filter in DS does strict equality
data "ovh_cloud_project_flavors" "flavors" {
  service_name = var.project_id
  name_filter = "r3-16-flex"
  region = var.region
}

// The image must be selected from it's region based list using name filtering, DS does not support direct selection
data ovh_cloud_project_images image{
  service_name  = var.project_id
  region = "SBG5"
}

locals {
  selected_image = one([
    for m in data.ovh_cloud_project_images.image.images : m if m.name == "Ubuntu 22.04"
  ])
  selected_flavor = one(data.ovh_cloud_project_flavors.flavors.flavors)
}

resource "ovh_cloud_project_instance" "simpl_vm" {
  service_name  = var.project_id
  region = var.region
  billing_period = "hourly"
  boot_from {
    image_id = local.selected_image.id
  }
  flavor {
    flavor_id = local.selected_flavor.id
  }
  name = "offering-enterprise-server-{UUID}-terraform"
  ssh_key_create {
    name       = "default-user-key"
    public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDjSFhpjNNDz3olIFuLdROifKJXekAu2CKQ7UyziJJOAPD2wP4eYEgTR6R12TnDHMDerNBLo8d/zIhkmmvF8zr4vBgB8nLHHV/hX6J8b1hg9o9ZtFY1czrdgEzjKtEEwqltQANWQqbg2i4cFDC96ZQRm8p/2XlKvdPkudHwnOqa6NtnE5vfBV0tk9uBbvr1mR8f9yMKpeTxyZUqOkhTZq8FIqS1h0n8Sh8CUYpTpsPilSspAs4xd/oR1FdINLGG4g9pJ/iRgsgMesQHb1qs8h/jws/XOE3Dg/+eDR5AsMz1DIuOjfVrT+xSFVtNxRQu5i6/mqad8NjeI+nR/TJjdnyS8k/JQEXWqOYIYOiozeueaP0fuulJuk0hf34dKrQqFp84Mqd7vE/Z4srdbyC1OfxCMhs3j7Ja9eujpAcp0aLl+mUGV9GKKANJlGmnt76YX5SPCKWEQb5plSXEbOkXPNCnJqF/x99AbPluSc3dYqBJmfhtu2w83jo6m+K50/F6eEU= cbeti@LXBU-2N877S3"
  }
  network {
    public = true
  }
  user_data = "I2Nsb3VkLWNvbmZpZwpob3N0bmFtZTogZGVmYXVsdC1zZXJ2ZXIgCnNzaF9wd2F1dGg6IHRydWUKY2hwYXNzd2Q6CiAgICBleHBpcmU6IGZhbHNlCnVzZXJzOgotIGRlZmF1bHQKLSBuYW1lOiB7bmFtZX0KICBwYXNzd2Q6IHtwd2R9CiAgc2hlbGw6IC9iaW4vYmFzaAogIGxvY2tfcGFzc3dkOiBmYWxzZQogIHN1ZG86IEFMTD0oQUxMKSBOT1BBU1NXRDpBTEwKICBncm91cHM6IHVzZXJzLCBhZG1pbiwgc3VkbwpydW5jbWQ6Ci0gZWNobyAicmVnZW5lcmF0aW5nIGhvc3Qga2V5cyIKLSBybSAtZiAvZXRjL3NzaC9zc2hfaG9zdF8qCi0gc3NoLWtleWdlbiAtQQotIGVjaG8gInJlc3RhcnRpbmcgc3NoZCIKLSBzeXN0ZW1jdGwgcmVzdGFydCBzc2hkCmRlYnVnOiB0cnVlCm91dHB1dDoKICBhbGw6ICJ8IHRlZSAtYSAvdmFyL2xvZy9jbG91ZC1pbml0LWRlYnVnLmxvZyIKZmluYWxfbWVzc2FnZTogIkRlZmF1bHQgVk0gQ2xvdWRpbml0IGRvbmUi"
}

// Values defined in outputs are placed in infrastructureDetails
output "vmIps" {
  depends_on = [ovh_cloud_project_instance.simpl_vm]
  value = tolist(ovh_cloud_project_instance.simpl_vm.addresses[*].ip)
}
