feat(slice-3): implement Proxmox VE REST API collector with guest agent IP resolution
This commit is contained in:
1 parent
951be389a1
commit
ca9163530f
4 files changed
+361
-1
No files matched your search
@@ -72,6 +72,26 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
for host in collector.collect():
|
||||
inv.add_host(host)
|
||||
|
||||
# Check for Proxmox environment variables
|
||||
import os
|
||||
from inventory_collector.collectors.proxmox import ProxmoxCollector
|
||||
|
||||
pve_url = os.getenv("PROXMOX_URL") or os.getenv("ANSIBLE_PROXMOX_URL")
|
||||
pve_token_id = os.getenv("PROXMOX_TOKEN_ID") or os.getenv("ANSIBLE_PROXMOX_TOKEN_ID")
|
||||
pve_token_secret = os.getenv("PROXMOX_TOKEN_SECRET") or os.getenv("ANSIBLE_PROXMOX_TOKEN_SECRET")
|
||||
verify_ssl = os.getenv("PROXMOX_VERIFY_SSL", "false").lower() in ("true", "1", "yes")
|
||||
|
||||
if pve_url and pve_token_id and pve_token_secret:
|
||||
sys.stderr.write(f"[INFO] Querying Proxmox VE API at {pve_url}...\n")
|
||||
pve_collector = ProxmoxCollector(
|
||||
url=pve_url,
|
||||
token_id=pve_token_id,
|
||||
token_secret=pve_token_secret,
|
||||
verify_ssl=verify_ssl
|
||||
)
|
||||
for host in pve_collector.collect():
|
||||
inv.add_host(host)
|
||||
|
||||
# Tracer bullet fallback if no hosts loaded
|
||||
if not inv.hosts:
|
||||
inv.add_host(HostRecord(
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import json
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from typing import Any, Dict, List, Optional
|
||||
from inventory_collector.collectors.base import BaseCollector
|
||||
from inventory_collector.models import HostRecord
|
||||
|
||||
class ProxmoxCollector(BaseCollector):
|
||||
"""Collects hypervisor nodes, virtual machines, and LXC containers from Proxmox VE API."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
url: str,
|
||||
token_id: str,
|
||||
token_secret: str,
|
||||
verify_ssl: bool = False,
|
||||
timeout: int = 10,
|
||||
default_user: str = "lain"
|
||||
) -> None:
|
||||
# Normalize base URL (strip trailing slashes and /api2/json if included)
|
||||
clean_url = url.rstrip("/")
|
||||
clean_url = re.sub(r"/api2/json/?$", "", clean_url)
|
||||
self.base_url = clean_url
|
||||
self.token_id = token_id
|
||||
self.token_secret = token_secret
|
||||
self.verify_ssl = verify_ssl
|
||||
self.timeout = timeout
|
||||
self.default_user = default_user
|
||||
|
||||
if not self.verify_ssl:
|
||||
self.ssl_context = ssl._create_unverified_context()
|
||||
else:
|
||||
self.ssl_context = ssl.create_default_context()
|
||||
|
||||
def _api_get(self, endpoint: str) -> Any:
|
||||
url = f"{self.base_url}/api2/json{endpoint}"
|
||||
req = urllib.request.Request(url)
|
||||
req.add_header("Authorization", f"PVEAPIToken={self.token_id}={self.token_secret}")
|
||||
req.add_header("Accept", "application/json")
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, context=self.ssl_context, timeout=self.timeout) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
return data.get("data", {})
|
||||
except urllib.error.HTTPError as e:
|
||||
# 500 often happens if guest agent is not running on VM
|
||||
return {}
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"[WARN] Proxmox API request failed for '{endpoint}': {e}\n")
|
||||
return {}
|
||||
|
||||
def _parse_tags(self, raw_tags: Optional[str]) -> List[str]:
|
||||
if not raw_tags:
|
||||
return []
|
||||
cleaned = re.sub(r"[,;]", " ", str(raw_tags))
|
||||
return [t.strip() for t in cleaned.split() if t.strip()]
|
||||
|
||||
def _resolve_dns_ip(self, name: str) -> Optional[str]:
|
||||
try:
|
||||
return socket.gethostbyname(name)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def _resolve_qemu_ip(self, node: str, vmid: int, vm_name: str) -> str:
|
||||
# 1. Try QEMU Guest Agent
|
||||
agent_data = self._api_get(f"/nodes/{node}/qemu/{vmid}/agent/network-get-interfaces")
|
||||
if isinstance(agent_data, dict) and "result" in agent_data:
|
||||
interfaces = agent_data.get("result", [])
|
||||
for iface in interfaces:
|
||||
if iface.get("name") == "lo":
|
||||
continue
|
||||
for addr in iface.get("ip-addresses", []):
|
||||
if addr.get("ip-address-type") == "ipv4":
|
||||
ip = addr.get("ip-address", "").strip()
|
||||
if ip and not ip.startswith("127.") and not ip.startswith("169.254."):
|
||||
return ip
|
||||
|
||||
# 2. Try VM hardware config
|
||||
config = self._api_get(f"/nodes/{node}/qemu/{vmid}/config")
|
||||
if isinstance(config, dict):
|
||||
for k in ("ipconfig0", "ipconfig1", "net0", "net1"):
|
||||
val = str(config.get(k, ""))
|
||||
m_ip = re.search(r"ip=([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", val)
|
||||
if m_ip:
|
||||
return m_ip.group(1)
|
||||
|
||||
# 3. Try DNS resolution
|
||||
dns_ip = self._resolve_dns_ip(vm_name)
|
||||
if dns_ip:
|
||||
return dns_ip
|
||||
|
||||
return ""
|
||||
|
||||
def _resolve_lxc_ip(self, node: str, vmid: int, ct_name: str) -> str:
|
||||
# Check container config
|
||||
config = self._api_get(f"/nodes/{node}/lxc/{vmid}/config")
|
||||
if isinstance(config, dict):
|
||||
for k in ("net0", "net1", "net2"):
|
||||
val = str(config.get(k, ""))
|
||||
m_ip = re.search(r"ip=([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)", val)
|
||||
if m_ip:
|
||||
return m_ip.group(1)
|
||||
|
||||
# Try DNS resolution
|
||||
dns_ip = self._resolve_dns_ip(ct_name)
|
||||
if dns_ip:
|
||||
return dns_ip
|
||||
|
||||
return ""
|
||||
|
||||
def collect(self) -> List[HostRecord]:
|
||||
records: List[HostRecord] = []
|
||||
nodes_data = self._api_get("/nodes")
|
||||
|
||||
if not isinstance(nodes_data, list):
|
||||
return records
|
||||
|
||||
for node_info in nodes_data:
|
||||
node_name = node_info.get("node")
|
||||
if not node_name:
|
||||
continue
|
||||
|
||||
# Hypervisor physical node
|
||||
node_ip = node_info.get("ip") or self._resolve_dns_ip(node_name) or ""
|
||||
records.append(HostRecord(
|
||||
name=node_name,
|
||||
ansible_host=node_ip,
|
||||
ansible_user="root",
|
||||
groups=["proxmox_nodes"],
|
||||
tags=["hypervisor", "pve"],
|
||||
variables={"proxmox_node": node_name, "proxmox_status": node_info.get("status", "unknown")},
|
||||
source="proxmox:node"
|
||||
))
|
||||
|
||||
# QEMU Virtual Machines
|
||||
qemu_list = self._api_get(f"/nodes/{node_name}/qemu")
|
||||
if isinstance(qemu_list, list):
|
||||
for vm in qemu_list:
|
||||
if vm.get("template") == 1:
|
||||
continue # Skip templates
|
||||
|
||||
vmid = vm.get("vmid")
|
||||
vm_name = vm.get("name") or f"vm-{vmid}"
|
||||
status = vm.get("status", "unknown")
|
||||
tags = self._parse_tags(vm.get("tags"))
|
||||
|
||||
ip = self._resolve_qemu_ip(node_name, vmid, vm_name)
|
||||
if not ip:
|
||||
tags.append("no-ip")
|
||||
sys.stderr.write(f"[WARN] No IP address discovered for VM '{vm_name}' (vmid: {vmid}, status: {status})\n")
|
||||
|
||||
groups = ["proxmox_vms", f"pve_node_{node_name}", f"status_{status}"]
|
||||
for t in tags:
|
||||
if t != "no-ip":
|
||||
groups.append(t)
|
||||
groups.append(f"tag_{t}")
|
||||
|
||||
records.append(HostRecord(
|
||||
name=vm_name,
|
||||
ansible_host=ip,
|
||||
ansible_user=self.default_user,
|
||||
groups=sorted(list(set(groups))),
|
||||
tags=sorted(list(set(tags))),
|
||||
variables={
|
||||
"proxmox_vmid": vmid,
|
||||
"proxmox_node": node_name,
|
||||
"proxmox_type": "qemu",
|
||||
"proxmox_status": status
|
||||
},
|
||||
source="proxmox:qemu"
|
||||
))
|
||||
|
||||
# LXC Containers
|
||||
lxc_list = self._api_get(f"/nodes/{node_name}/lxc")
|
||||
if isinstance(lxc_list, list):
|
||||
for ct in lxc_list:
|
||||
if ct.get("template") == 1:
|
||||
continue # Skip templates
|
||||
|
||||
vmid = ct.get("vmid")
|
||||
ct_name = ct.get("name") or f"ct-{vmid}"
|
||||
status = ct.get("status", "unknown")
|
||||
tags = self._parse_tags(ct.get("tags"))
|
||||
|
||||
ip = self._resolve_lxc_ip(node_name, vmid, ct_name)
|
||||
if not ip:
|
||||
tags.append("no-ip")
|
||||
sys.stderr.write(f"[WARN] No IP address discovered for LXC container '{ct_name}' (vmid: {vmid}, status: {status})\n")
|
||||
|
||||
groups = ["proxmox_lxc", f"pve_node_{node_name}", f"status_{status}"]
|
||||
for t in tags:
|
||||
if t != "no-ip":
|
||||
groups.append(t)
|
||||
groups.append(f"tag_{t}")
|
||||
|
||||
records.append(HostRecord(
|
||||
name=ct_name,
|
||||
ansible_host=ip,
|
||||
ansible_user=self.default_user,
|
||||
groups=sorted(list(set(groups))),
|
||||
tags=sorted(list(set(tags))),
|
||||
variables={
|
||||
"proxmox_vmid": vmid,
|
||||
"proxmox_node": node_name,
|
||||
"proxmox_type": "lxc",
|
||||
"proxmox_status": status
|
||||
},
|
||||
source="proxmox:lxc"
|
||||
))
|
||||
|
||||
return records
|
||||
Reference in new issue
Block a user