homelab_cluster/tofu/main.tf

118 lines
2.6 KiB
HCL

terraform {
required_providers {
libvirt = {
source = "dmacvicar/libvirt"
version = "0.8.3"
}
}
}
provider "libvirt" {
uri = var.libvirt_uri
}
# --- Base Image Handling ---
resource "libvirt_volume" "base_image" {
name = var.base_image_name
pool = var.libvirt_pool
source = var.base_image_url
format = "qcow2"
}
# --- Cloud-Init Configuration ---
data "cloudinit_config" "common_init" {
gzip = false
base64_encode = false
part {
content_type = "text/cloud-config"
content = templatefile("${path.module}/cloud_init.cfg.yml", {
user = var.vm_user
ssh_authorized_keys = [chomp(file(pathexpand(var.ssh_public_key_path)))]
})
}
}
resource "libvirt_cloudinit_disk" "common_iso" {
name = "${var.cluster_name}-common-init.iso"
user_data = data.cloudinit_config.common_init.rendered
pool = var.libvirt_pool
}
# --- K3s Server Node ---
resource "libvirt_volume" "server_disk" {
name = "${var.server_hostname}-disk.qcow2"
base_volume_id = libvirt_volume.base_image.id
pool = var.libvirt_pool
size = var.server_disk_size
format = "qcow2"
}
resource "libvirt_domain" "server" {
name = var.server_hostname
memory = var.server_memory
vcpu = var.server_vcpu
cloudinit = libvirt_cloudinit_disk.common_iso.id
network_interface {
network_name = var.libvirt_network_name
addresses = [var.server_ip]
wait_for_lease = true
}
disk {
volume_id = libvirt_volume.server_disk.id
}
console {
type = "pty"
target_port = "0"
target_type = "serial"
}
graphics {
type = "spice"
listen_type = "address"
autoport = true
}
}
# --- K3s Agent Nodes ---
resource "libvirt_volume" "agent_disk" {
count = var.agent_count
name = "${var.agent_hostname_prefix}-${count.index + 1}-disk.qcow2"
base_volume_id = libvirt_volume.base_image.id
pool = var.libvirt_pool
size = var.agent_disk_size
format = "qcow2"
}
resource "libvirt_domain" "agent" {
count = var.agent_count
name = "${var.agent_hostname_prefix}-${count.index + 1}"
memory = var.agent_memory
vcpu = var.agent_vcpu
cloudinit = libvirt_cloudinit_disk.common_iso.id
network_interface {
network_name = var.libvirt_network_name
addresses = [var.agent_ips[count.index]]
wait_for_lease = true
}
disk {
volume_id = libvirt_volume.agent_disk[count.index].id
}
console {
type = "pty"
target_port = "0"
target_type = "serial"
}
graphics {
type = "spice"
listen_type = "address"
autoport = true
}
}