Files
public/Infrastrucutre as Code/Terraform/main.tf
T
2026-06-09 10:20:07 +03:00

109 lines
2.6 KiB
Terraform

locals {
ansible_repo_path = var.ansible_repo_path != "" ? var.ansible_repo_path : "${path.module}/../ansible"
}
resource "proxmox_vm_qemu" "vm" {
for_each = var.vms
agent = 1
skip_ipv6 = true
vmid = each.value.vmid
name = each.value.name
target_node = each.value.target_node
clone = each.value.template
onboot = each.value.onboot
os_type = "other"
cpu {
type = "host"
numa = true
cores = each.value.cores
sockets = each.value.sockets
}
memory = each.value.memory
balloon = 0
scsihw = "virtio-scsi-pci"
bootdisk = "scsi0"
disk {
slot = "scsi0"
type = "disk"
storage = each.value.disk_storage
size = each.value.disk_size
format = "qcow2"
discard = true
}
network {
id = 0
bridge = each.value.bridge
model = "virtio"
macaddr = each.value.macaddr
tag = each.value.vlan != 0 ? each.value.vlan : null
}
lifecycle {
ignore_changes = [
usb,
]
}
serial {
id = 0
}
tags = length(each.value.tags) > 0 ? join(",", each.value.tags) : null
}
resource "null_resource" "wait_for_ssh" {
for_each = var.vms
depends_on = [proxmox_vm_qemu.vm]
connection {
type = "ssh"
host = each.value.ip
user = "ansible"
private_key = file("~/.ssh/auto")
timeout = "5m"
}
provisioner "local-exec" {
command = <<EOT
echo "Waiting for SSH on ${each.value.ip}..."
for i in {1..30}; do
if ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i ~/.ssh/auto ansible@${each.value.ip} 'echo SSH Ready' >/dev/null 2>&1; then
echo "✅ SSH is up!"
exit 0
fi
echo "Retry $i: SSH not ready yet..."
sleep 10
done
echo "❌ SSH did not become available on ${each.value.ip} after timeout."
exit 1
EOT
}
}
resource "local_file" "host_tags" {
for_each = var.vms
content = templatefile("${path.module}/host_tags.yml.tpl", {
vmid = each.value.vmid
name = each.value.name
target_node = each.value.target_node
template = each.value.template
cores = each.value.cores
sockets = each.value.sockets
memory = each.value.memory
bridge = each.value.bridge
macaddr = each.value.macaddr
disk_size = each.value.disk_size
disk_storage = each.value.disk_storage
ip = each.value.ip
vlan = each.value.vlan
tags = each.value.tags
})
filename = "${local.ansible_repo_path}/host_vars/${each.value.name}/host_tags.yml"
}