# vultr instances meant for running k3s cluster
# these are working concept notes, although it is not used



resource "vultr_instance" "k3s_server" {
    count = 1
    hostname        = "k3s-server-${count.index}"
    plan            = "vc2-2c-2gb"
    region          = "ord"
    backups         = "disabled"
    ddos_protection = "false"
    os_id           = 1743
    enable_ipv6     = true
    label = "k3s"
    tags = ["futureporn", "k3s", "server"]
    ssh_key_ids = [local.envs.VULTR_SSH_KEY_ID]
    vpc2_ids = [
      vultr_vpc2.futureporn_vpc2.id
    ]
}

resource "vultr_instance" "k3s_agent" {
    count = 3
    hostname        = "k3s-agent-${count.index}"
    plan            = "vc2-2c-2gb"
    region          = "ord"
    backups         = "disabled"
    ddos_protection = "false"
    os_id           = 1743
    enable_ipv6     = true
    label = "k3s"
    tags = ["futureporn", "k3s", "agent"]
    ssh_key_ids = [local.envs.VULTR_SSH_KEY_ID]
    vpc2_ids = [
      vultr_vpc2.futureporn_vpc2.id
    ]
}


resource "ansible_host" "k3s_server_vps" {
  for_each = { for idx, host in vultr_instance.k3s_server : idx => host }
  name = each.value.hostname
  groups = ["server"]
  variables = {
    ansible_host = each.value.main_ip
  }
}

resource "ansible_host" "k3s_agent_vps" {
  for_each = { for idx, host in vultr_instance.k3s_agent : idx => host }
  name = each.value.hostname
  groups = ["agent"]
  variables = {
    ansible_host = each.value.main_ip
  }
}

resource "ansible_group" "server" {
  name = "server"
}

resource "ansible_group" "agent" {
  name = "agent"
}

resource "ansible_group" "k3s_cluster" {
  name = "k3s_cluster"
  children = [
    "server",
    "agent"
  ]
  variables = {
    k3s_version = "v1.31.6+k3s1"
    token = local.envs.K3S_TOKEN
    api_endpoint = "{{ hostvars[groups['server'][0]]['ansible_host'] | default(groups['server'][0]) }}"
    # use_external_database = true
    # extra_server_args = "--datastore-endpoint={{ local.envs.K3S_DATABASE_URL }}"
  }
}