Files
cluster-knaster/platform/proxmox/scripts/refresh-vm-access.sh
T
2026-10-15 11:57:57 +02:00

48 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
# Zugang zu den GPU-VMs und Infra-Containern auffrischen (läuft auf ops, im Verzeichnis platform/proxmox/tofu, mit
# geladenem /root/.config/knaster/tofu.env). Nötig nach jedem VM-Neustart, solange die Gäste per
# DHCP ohne Reservierung laufen (D5): Adressen können wechseln (12.10. zwei VMs vertauscht).
#
# 1. aktuelle Adressen per qemu-guest-agent in den tofu-State holen (refresh-only)
# 2. ../ansible/inventory.generated.yml neu schreiben
# 3. Hostschlüssel über den Agenten lesen (Vertrauensweg Proxmox statt ssh-keyscan) und in
# ~/.ssh/known_hosts eintragen; vorher wartet das Skript, bis cloud-init fertig ist.
set -euo pipefail
tofu apply -refresh-only -auto-approve -input=false -no-color >/dev/null
tofu output -raw ansible_inventory > ../ansible/inventory.generated.yml
# GPU-VMs und Dienst-VMs (k3s, D6) gleich behandeln
for out in gpu_vms service_vms; do tofu output -json "$out"; done | python3 -c '
import json, sys
dec = json.JSONDecoder(); s = sys.stdin.read(); i = 0
while i < len(s):
while i < len(s) and s[i].isspace(): i += 1
if i >= len(s): break
obj, i = dec.raw_decode(s, i)
for name, v in obj.items():
if v["ipv4"]:
print(name, v["node"], v["vmid"], v["ipv4"])
' | while read -r name node vmid ip; do
ssh -n "$node" "qm guest exec $vmid --timeout 900 -- cloud-init status --wait" >/dev/null || true
key=$(ssh -n "$node" "qm guest exec $vmid -- cat /etc/ssh/ssh_host_ed25519_key.pub" \
| python3 -c 'import json, sys; print(json.load(sys.stdin)["out-data"].strip())')
ssh-keygen -R "$ip" >/dev/null 2>&1 || true
echo "$ip $key" >> ~/.ssh/known_hosts
echo "$name ($ip): $(ssh-keygen -lf <(echo "$ip $key") | awk '{print $2}')"
done
# Infra-Container: Hostschlüssel über pct exec (Container hat keinen Gast-Agenten)
tofu output -json infra_containers | python3 -c '
import json, sys
for name, v in json.load(sys.stdin).items():
if v.get("ipv4"):
print(name, v["node"], v["vmid"], v["ipv4"])
' | while read -r name node vmid ip; do
node=$(ssh -n pve44 "pvesh get /cluster/resources --type vm --output-format json" | python3 -c "import json,sys; print(next(r['node'] for r in json.load(sys.stdin) if r['vmid']==$vmid))")
key=$(ssh -n "$node" "pct exec $vmid -- cat /etc/ssh/ssh_host_ed25519_key.pub")
ssh-keygen -R "$ip" >/dev/null 2>&1 || true
echo "$ip $key" >> ~/.ssh/known_hosts
echo "$name ($ip, $node): $(ssh-keygen -lf <(echo "$ip $key") | awk '{print $2}')"
done