Merge pull request 'fix: twelve open bugs, set_vlan uplink first (#37, #30, #23, #22, #21, #20, #19, #18, #17, #15, #12, #3)' (#40) from fix/bugs-2026-11 into main
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 14s
driver / types (push) Successful in 1m27s
driver / test (3.12) (push) Successful in 1m43s
driver / lowest (push) Successful in 37s
driver / test (3.13) (push) Successful in 1m24s
driver / build (push) Successful in 28s
driver / security (push) Successful in 1m17s
CI / driver (push) Successful in 3m33s
driver / publish (push) Skipped

This commit was merged in pull request #40.
This commit is contained in:
christianmanivong committed 2026-11-01 22:50:18 +00:00
commit a8d73d95b4
19 files changed
+1067 -145

No files matched your search

+22 -7
View File
@@ -345,17 +345,17 @@ class ProxmoxDriver(
import paramiko
if self._ssh_client is None:
ssh_pass = self._ssh_password or self.password
# A key is tried first; paramiko falls back to the password.
connect_kwargs: _JsonDict = {
"username": self._ssh_username or self.username,
"timeout": self.timeout,
}
if self._ssh_key and not ssh_pass:
from io import StringIO as _StringIO
connect_kwargs["pkey"] = paramiko.RSAKey.from_private_key(_StringIO(self._ssh_key))
else:
connect_kwargs["password"] = ssh_pass
password = self._ssh_password or self.password
if password:
connect_kwargs["password"] = password
pkey = _load_private_key(self._ssh_key) if self._ssh_key else None
if pkey is not None:
connect_kwargs["pkey"] = pkey
client = paramiko.SSHClient()
try:
HostKeyCheck(self.optional_args, self.hostname, 22).connect(
@@ -513,3 +513,18 @@ class ProxmoxDriver(
def cli(self, commands: list[str], encoding: str = "text") -> dict[str, str]:
"""Execute a list of shell commands and return their outputs."""
return {cmd: self._exec_ssh_command(cmd) for cmd in commands}
def _load_private_key(text: str) -> Any: # paramiko.PKey; paramiko is imported lazily
"""The SSH private key in *text*, whatever its type, or None when it cannot be read."""
import io
import paramiko
for key_class in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
try:
return key_class.from_private_key(io.StringIO(text))
except (paramiko.SSHException, ValueError):
continue
logger.warning("The SSH private key could not be read; logging in with the password")
return None
+12 -12
View File
@@ -26,26 +26,26 @@ class ProxmoxLLDPMixin:
"""Mixin providing LLDP NAPALM methods."""
def get_lldp_neighbors(self) -> dict[str, list[_JsonDict]]:
"""Return LLDP neighbours (requires lldpd on the Proxmox node)."""
"""Return LLDP neighbours (requires lldpd on the Proxmox node).
lldpcli prints one ``Interface:`` block per neighbour, so a port with
several neighbours appears once for each of them.
"""
result: dict[str, list[_JsonDict]] = {}
raw = self._exec_ssh_command("lldpcli show neighbors summary 2>/dev/null || true")
current_iface = ""
current: _JsonDict | None = None
for line in raw.splitlines():
m_iface = re.match(r"^\s*Interface:\s+(\S+?),?\s", line)
if m_iface:
current_iface = m_iface.group(1)
result.setdefault(current_iface, [])
current = {"hostname": "", "port": ""}
result.setdefault(m_iface.group(1), []).append(current)
continue
m_sys = re.match(r"^\s*SysName:\s+(.+)", line)
m_port = re.match(r"^\s*PortID:\s+\S+\s+(.+)", line)
if m_sys and current_iface:
hostname = m_sys.group(1).strip()
if result[current_iface]:
result[current_iface][-1]["hostname"] = hostname
else:
result[current_iface].append({"hostname": hostname, "port": ""})
if m_port and current_iface and result[current_iface]:
result[current_iface][-1]["port"] = m_port.group(1).strip()
if m_sys and current is not None:
current["hostname"] = m_sys.group(1).strip()
if m_port and current is not None:
current["port"] = m_port.group(1).strip()
return result
def get_lldp_neighbors_detail(self, interface: str = "") -> dict[str, list[_JsonDict]]:
+113
View File
@@ -0,0 +1,113 @@
"""NTP statistics (``get_ntp_stats``) from chrony or ntpd, in NAPALM's NTPStats shape.
Proxmox VE ships chrony; ntpd is read only where chrony is not installed.
chrony is read in its CSV mode (``chronyc -c``): ``sources`` names each source
with its state, ``sourcestats`` adds the spread of its offset, reported as
jitter. chrony reports no delay per source, so ``delay`` is 0.0. Times are in
milliseconds and the poll interval in seconds, as ``ntpq -pn`` gives them.
"""
from __future__ import annotations
import re
from typing import Any
CHRONY_SOURCES_MARK = "CHRONY_SOURCES"
CHRONY_SOURCESTATS_MARK = "CHRONY_SOURCESTATS"
#: chrony when it is installed, ntpd's ntpq otherwise.
NTP_STATS_COMMAND = (
"if command -v chronyc >/dev/null 2>&1; then "
f"echo {CHRONY_SOURCES_MARK}; chronyc -n -c sources; "
f"echo {CHRONY_SOURCESTATS_MARK}; chronyc -n -c sourcestats; "
"else ntpq -pn; fi 2>/dev/null"
)
#: chrony's source mode as ntpq's type: server (unicast), peer (symmetric), refclock (local).
_CHRONY_TYPES = {"^": "u", "=": "s", "#": "l"}
_MS_PER_S = 1000.0
#: ``*192.168.1.1 10.0.0.1 4 u 12 64 377 1.234 0.567 0.123``; the first
#: column is the tally mark, a space for a peer without one.
_NTPQ_LINE = re.compile(
r"^([ *+#ox.-])(\S+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\d+)"
r"\s+([-\d.]+)\s+([-\d.]+)\s+([-\d.]+)"
)
def parse_ntp_stats(output: str) -> list[dict[str, Any]]:
"""The NTPStats list in the output of :data:`NTP_STATS_COMMAND`."""
if output.lstrip().startswith(CHRONY_SOURCES_MARK):
return parse_chrony(output)
return parse_ntpq(output)
def parse_chrony(output: str) -> list[dict[str, Any]]:
"""Sources and their statistics from ``chronyc -n -c sources`` / ``sourcestats``."""
sources, _, sourcestats = output.partition(CHRONY_SOURCESTATS_MARK)
jitter = _chrony_jitter(sourcestats)
stats = []
for line in sources.splitlines():
fields = line.strip().split(",")
if len(fields) < 10:
continue
mode, state, name, stratum, poll, reach, last_rx, _, offset, _ = fields[:10]
try:
stats.append(
{
"remote": name,
"referenceid": "",
"synchronized": state == "*",
"stratum": int(stratum),
"type": _CHRONY_TYPES.get(mode, ""),
"when": last_rx,
"hostpoll": 2 ** int(poll),
"reachability": int(reach),
"delay": 0.0,
"offset": float(offset) * _MS_PER_S,
"jitter": jitter.get(name, 0.0),
}
)
except ValueError:
continue
return stats
def _chrony_jitter(sourcestats: str) -> dict[str, float]:
"""Each source's offset standard deviation in ms (``sourcestats``' last column)."""
jitter = {}
for line in sourcestats.splitlines():
fields = line.strip().split(",")
if len(fields) < 8:
continue
try:
jitter[fields[0]] = float(fields[7]) * _MS_PER_S
except ValueError:
continue
return jitter
def parse_ntpq(output: str) -> list[dict[str, Any]]:
"""Peers from ``ntpq -pn``."""
stats = []
for line in output.splitlines():
m = _NTPQ_LINE.match(line)
if not m:
continue
tally, remote, refid, stratum, kind, when, poll, reach, delay, offset, jitter = m.groups()
stats.append(
{
"remote": remote,
"referenceid": refid,
"synchronized": tally == "*",
"stratum": int(stratum),
"type": kind,
"when": when,
"hostpoll": int(poll),
"reachability": int(reach),
"delay": float(delay),
"offset": float(offset),
"jitter": float(jitter),
}
)
return stats
+7 -3
View File
@@ -23,6 +23,10 @@ import napalm.base.constants as C
_JsonDict = dict[str, Any]
#: One reply in iputils' ping output, by address or by name with the address
#: in brackets: "64 bytes from dns.google (8.8.4.4): icmp_seq=1 ttl=118 time=10.5 ms".
_PING_REPLY = re.compile(r"bytes from (?:\S+ \()?([0-9a-fA-F.:]+)\)?: .*?time=([\d.]+) ms")
class ProxmoxRoutingMixin:
"""Mixin providing routing NAPALM methods (get_route_to, ping, traceroute)."""
@@ -90,9 +94,9 @@ class ProxmoxRoutingMixin:
rtt_std = float(m_rtt.group(4)) if m_rtt else 0.0
# Individual probe lines
probes = []
for m_probe in re.finditer(r"icmp_seq=\d+.*?time=([\d.]+) ms.*?from ([\d.a-fA-F:]+)", raw):
probes.append({"ip_address": m_probe.group(2), "rtt": float(m_probe.group(1))})
probes = [
{"ip_address": m.group(1), "rtt": float(m.group(2))} for m in _PING_REPLY.finditer(raw)
]
return {
"success": {
+11
View File
@@ -33,6 +33,17 @@ _JsonDict = dict[str, Any]
class ProxmoxSDNMixin:
"""Mixin providing SDN, VLAN and network-instance NAPALM methods."""
#: Name prefixes of Proxmox-internal and runtime virtual interfaces, never a switch uplink.
_VIRTUAL_IFACE_PREFIXES: tuple[str, ...] = (
"fwpr", # Proxmox firewall proxy veth
"fwln", # Proxmox firewall link veth
"tap", # VM tap devices
"veth", # generic veth pairs (containers)
"virbr", # libvirt bridges
"docker", # Docker virtual interfaces
"lxcbr", # LXC bridges
)
def _get_sdn_zones(self) -> list[_JsonDict]:
try:
return self._api.cluster.sdn.zones.get() or [] # type: ignore[union-attr]
+142 -99
View File
@@ -26,8 +26,11 @@ import re
import shlex
from typing import Any
from napalm.base.exceptions import CommandErrorException
from napalm_device_types import APT_UPGRADABLE_COMMAND, parse_apt_upgradable
from napalm_proxmox.ntp import NTP_STATS_COMMAND, parse_ntp_stats
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
@@ -45,6 +48,71 @@ _SUBSCRIPTION_STATUS = {
_PACKAGE_NAME = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_.+:~-]*$")
#: What may stand in an snmpd.conf value: no whitespace, no quote, no comment.
_SNMP_WORD = re.compile(r'^[^\s"#]+$')
#: The net-snmp agent's configuration file.
_SNMPD_CONF = "/etc/snmp/snmpd.conf"
#: Exit status 0 when the node is a cluster member. pvecm itself decides
#: membership by /etc/pve/corosync.conf; /etc/corosync/corosync.conf is the
#: local copy every member keeps, there even when /etc/pve is not mounted.
#: Not ``pvecm status``: it also fails on a member whose corosync is down.
_CLUSTER_MEMBER_CHECK = "[ -e /etc/pve/corosync.conf ] || [ -e /etc/corosync/corosync.conf ]"
def _rename_in_hosts(hosts: str, old_short: str, new_short: str, new_domain: str | None) -> str:
"""*hosts* (an /etc/hosts) with the node's names renamed from *old_short*.
Only whole names change: ``old_short`` becomes ``new_short``, and
``old_short.<domain>`` becomes ``new_short.<new_domain>`` (the old domain
kept when *new_domain* is None). Other names that merely start with the
old name (``pve-backup``) and comments stay as they are.
"""
def rename(match: re.Match[str]) -> str:
name = match.group(0)
if name == old_short:
return new_short
if name.startswith(f"{old_short}."):
return f"{new_short}.{new_domain or name[len(old_short) + 1 :]}"
return name
lines = []
for line in hosts.splitlines(keepends=True):
entry, hash_, comment = line.partition("#")
lines.append(re.sub(r"\S+", rename, entry) + hash_ + comment)
return "".join(lines)
#: Proxmox's superuser, whatever the ACL says.
_PVE_SUPERUSER = "root@pam"
#: The role that makes a Proxmox user an administrator of the node.
_PVE_ADMIN_ROLE = "Administrator"
#: Regular login accounts: Debian gives them uids from 1000 up; 65534 is nobody.
_FIRST_REGULAR_UID = 1000
_NOBODY_UID = 65534
def _words(value: Any, sep: str | None = None) -> list[str]:
return [w.strip() for w in str(value or "").split(sep) if w.strip()]
def _user_entry(level: int) -> _JsonDict:
# NAPALM's get_users shape; the password is never read.
return {"level": level, "password": "", "sshkeys": []} # nosec B105
def _login_accounts(passwd: str) -> list[tuple[str, int]]:
"""``(name, uid)`` of root and every regular account in *passwd*."""
accounts = []
for line in passwd.splitlines():
parts = line.split(":")
if len(parts) < 7:
continue
try:
uid = int(parts[2])
except ValueError:
continue
if uid == 0 or _FIRST_REGULAR_UID <= uid < _NOBODY_UID:
accounts.append((parts[0], uid))
return accounts
def _net(value: str) -> str:
@@ -137,36 +205,8 @@ class ProxmoxSystemMixin:
return servers
def get_ntp_stats(self) -> list[_JsonDict]:
"""Return NTP synchronisation statistics from chronyc/ntpq output."""
raw = self._exec_ssh_command(
"chronyc -n tracking 2>/dev/null || ntpq -pn 2>/dev/null || true"
)
stats: list[_JsonDict] = []
for line in raw.splitlines():
line = line.strip()
# ntpq -pn format: *remote refid st t when poll reach delay offset jitter
m = re.match(
r"^([\*\+\-\s])([\d.]+)\s+([\d.]+)\s+(\d+)\s+\S+\s+(\S+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+([-\d.]+)\s+([\d.]+)",
line,
)
if m:
synced = m.group(1).strip() == "*"
stats.append(
{
"remote": m.group(2),
"referenceid": m.group(3),
"synchronized": synced,
"stratum": int(m.group(4)),
"type": "",
"when": m.group(5),
"hostpoll": int(m.group(6)),
"reachability": int(m.group(7)),
"delay": float(m.group(8)),
"offset": float(m.group(9)),
"jitter": float(m.group(10)),
}
)
return stats
"""Return NTP synchronisation statistics from chrony, or ntpd where chrony is missing."""
return parse_ntp_stats(self._exec_ssh_command(NTP_STATS_COMMAND))
# ------------------------------------------------------------------ #
# get_snmp_information
@@ -213,55 +253,52 @@ class ProxmoxSystemMixin:
def get_users(self) -> dict[str, _JsonDict]:
"""Return users configured on the Proxmox node.
Reads from both the Proxmox access/users API and local /etc/passwd.
Proxmox's own users (``/access/users``) at level 15 when they hold the
Administrator role on the whole datacenter (``/``), directly or through
a group, 1 otherwise; ``root@pam`` is always 15. Then the node's login
accounts from the passwd database: root (15) and regular users
(uid 1000 and up, without ``nobody``) at 0; system accounts are left out.
"""
result: dict[str, _JsonDict] = {}
try:
pve_users = self._api.access.users.get() or [] # type: ignore[union-attr]
except Exception as exc:
logger.debug("Failed to fetch Proxmox users: %s", exc)
pve_users = []
for user in pve_users:
admins, admin_groups = self._pve_administrators()
for user in self._pve_users():
uid = user.get("userid", "")
if not uid:
continue
# Proxmox roles: Administrator -> 15, otherwise 1
level = 1
try:
roles = self._api.access.users(uid).get() or {} # type: ignore[union-attr]
if "Administrator" in str(roles):
level = 15
except Exception as exc:
logger.debug("Failed to fetch roles for user %s: %s", uid, exc)
result[uid] = {
"level": level,
# NAPALM's get_users shape; the password is never read.
"password": "", # nosec B105
"sshkeys": [],
}
groups = set(_words(user.get("groups"), sep=","))
is_admin = uid == _PVE_SUPERUSER or uid in admins or bool(groups & admin_groups)
result[uid] = _user_entry(15 if is_admin else 1)
# Merge local OS users from /etc/passwd
raw = self._exec_ssh_command("getent passwd 2>/dev/null || cat /etc/passwd")
for line in raw.splitlines():
parts = line.split(":")
if len(parts) < 7:
continue
uname, _, uid_str, *_ = parts
try:
uid_int = int(uid_str)
except ValueError:
continue
if uname not in result and uid_int < 1000 or uid_int == 0:
result[uname] = {
"level": 15 if uid_int == 0 else 0,
# NAPALM's get_users shape; the password is never read.
"password": "", # nosec B105
"sshkeys": [],
}
for uname, uid_int in _login_accounts(raw):
result.setdefault(uname, _user_entry(15 if uid_int == 0 else 0))
return result
def _pve_users(self) -> list[_JsonDict]:
try:
return self._api.access.users.get() or [] # type: ignore[union-attr]
except Exception as exc:
logger.debug("Failed to fetch Proxmox users: %s", exc)
return []
def _pve_administrators(self) -> tuple[set[str], set[str]]:
"""Users and groups holding the Administrator role on ``/`` (``/access/acl``)."""
try:
acl = self._api.access.acl.get() or [] # type: ignore[union-attr]
except Exception as exc:
logger.debug("Failed to fetch the Proxmox ACL: %s", exc)
acl = []
users: set[str] = set()
groups: set[str] = set()
for entry in acl:
if entry.get("path") != "/" or entry.get("roleid") != _PVE_ADMIN_ROLE:
continue
if entry.get("type") == "user":
users.add(entry.get("ugid", ""))
elif entry.get("type") == "group":
groups.add(entry.get("ugid", ""))
return users, groups
# ------------------------------------------------------------------ #
# Kernel facts (KernelFactsMixin supplies get_kernel_facts)
# ------------------------------------------------------------------ #
@@ -448,11 +485,17 @@ class ProxmoxSystemMixin:
if not re.match(r"^[a-zA-Z0-9_\-\+\.]+$", pkg):
raise ValueError(f"Invalid package name: {pkg!r}")
pkg_args = " ".join(packages)
output = self._exec_ssh_command(
"DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade -y "
f"{pkg_args} 2>&1 || true"
output, status = self._rc(
f"DEBIAN_FRONTEND=noninteractive apt-get install --only-upgrade -y {pkg_args}"
)
return {"success": True, "output": output}
if status == 0:
return {"success": True, "output": output}
error = (
f"apt-get exited with status {status}"
if status >= 0
else "apt-get's exit status could not be read"
)
return {"success": False, "output": output, "error": error}
# ------------------------------------------------------------------ #
# SNMP / Health
@@ -527,8 +570,12 @@ class ProxmoxSystemMixin:
return self._step(command, done)
def _write_apt_file(self, path: str, content: str) -> dict:
return self._write_root_file(path, content)
def _write_root_file(self, path: str, content: str) -> dict:
"""Write *content* to *path* as root, mode 644, through a temporary file."""
encoded = base64.b64encode(content.encode()).decode()
# No ``exit`` here: ``_rc`` reads the status after the command's braces.
# No ``exit`` here: it would end the shell before ``_rc`` reads the status.
return self._step(
f'umask 077 && t=$(mktemp) && echo {encoded} | base64 -d > "$t" && '
f'install -m 644 -o root -g root "$t" {shlex.quote(path)}; '
@@ -559,13 +606,7 @@ class ProxmoxSystemMixin:
)
def _write_snmp_agent_config(self, settings: dict) -> dict:
encoded = base64.b64encode(render_snmpd_conf(settings).encode()).decode()
return self._step(
f'umask 077 && t=$(mktemp) && echo {encoded} | base64 -d > "$t" && '
f'install -m 644 -o root -g root "$t" /etc/snmp/snmpd.conf; '
's=$?; rm -f "$t"; exit $s',
"wrote /etc/snmp/snmpd.conf",
)
return self._write_root_file(_SNMPD_CONF, render_snmpd_conf(settings))
def _allow_snmp_sources(self, settings: dict) -> dict:
sources = [_net(s) for s in settings.get("allowed_sources", [])]
@@ -582,6 +623,18 @@ class ProxmoxSystemMixin:
"snmpd enabled and running",
)
def _refuse_clustered_node(self) -> None:
_, status = self._rc(_CLUSTER_MEMBER_CHECK)
if status == 0:
raise CommandErrorException(
"set_hostname refused: the node is part of a cluster; rename a cluster"
" member by Proxmox's own procedure, not in place"
)
if status != 1:
raise CommandErrorException(
"set_hostname refused: could not tell whether the node is part of a cluster"
)
def set_hostname(self, new_hostname: str) -> None:
"""Set the system hostname on the Proxmox node.
@@ -599,16 +652,16 @@ class ProxmoxSystemMixin:
7. Proxmox node TLS certificate — regenerated via
``pvenode cert create --overwrite``.
**Important**: the Proxmox *node name* (shown in the web UI and stored
in ``/etc/pve/nodes/<name>/``) only changes after a full reboot.
Until then the web UI still shows the old node name, but the OS-level
hostname and the SSL certificate already reflect the new value.
The Proxmox *node name* (web UI, ``/etc/pve/nodes/<name>/``) only
changes after a reboot. Accepts a bare hostname or an FQDN.
Accepts a bare hostname (``pve-see``) or an FQDN
(``pve-see.see.local``).
Raises CommandErrorException, before changing anything, on a cluster
member (a corosync.conf exists): its rename is the cluster's procedure.
"""
import base64 as _b64
self._refuse_clustered_node()
if "." in new_hostname:
short_hostname, domain = new_hostname.split(".", 1)
fqdn = new_hostname
@@ -633,17 +686,7 @@ class ProxmoxSystemMixin:
# write back via base64 to avoid shell-escaping issues.
if old_short and old_short != short_hostname:
hosts_raw = self._exec_ssh_command("cat /etc/hosts 2>/dev/null")
# Replace whole-word occurrences of the old short hostname.
# Both "hostname" and "hostname.domain" forms are covered because
# the new value is the full fqdn when a domain was given.
import re as _re
new_replace = fqdn if domain else short_hostname
hosts_new = _re.sub(
r"\b" + _re.escape(old_short) + r"\b",
new_replace,
hosts_raw,
)
hosts_new = _rename_in_hosts(hosts_raw, old_short, short_hostname, domain)
hosts_b64 = _b64.b64encode(hosts_new.encode()).decode()
self._exec_ssh_command(
f"echo {hosts_b64} | base64 -d > /tmp/_netork_hosts"
+34 -19
View File
@@ -186,12 +186,7 @@ class ProxmoxVMProvisionMixin:
timeout=30,
)
if "EXISTS" not in exists:
_logger.info(f"Downloading cloud image {image_url} -> {local_path}")
self._run_node_command(
f"wget -q -O {local_path}.tmp '{image_url}' "
f"&& mv {local_path}.tmp {local_path}",
timeout=timeout,
)
self._fetch_image(image_url, local_path, timeout)
if not image_checksum:
return local_path
@@ -216,6 +211,20 @@ class ProxmoxVMProvisionMixin:
raise AssertionError("unreachable") # loop always returns or raises above
def _fetch_image(self, image_url: str, local_path: str, timeout: int) -> None:
"""Download *image_url* to *local_path* on the node, through a ``.tmp``.
wget runs with ``-nv`` so its reason ("No space left on device")
reaches the error, and a failed download leaves no partial ``.tmp``.
"""
_logger.info(f"Downloading cloud image {image_url} -> {local_path}")
tmp = f"{local_path}.tmp"
self._run_node_command(
f"wget -nv -O {tmp} '{image_url}' && mv {tmp} {local_path} "
f"|| {{ s=$?; rm -f {tmp}; exit $s; }}",
timeout=timeout,
)
def _cloud_image_on_node(self, image_url: str, image_checksum: str | None, timeout: int) -> str:
"""The node path of the image, downloaded, verified and unpacked.
@@ -736,9 +745,9 @@ class ProxmoxVMProvisionMixin:
cloud_init_args[f"ipconfig{i}"] = "ip=dhcp"
if ssh_public_keys:
# URL-encode SSH keys for Proxmox API
sshkeys = ";".join(ssh_public_keys)
cloud_init_args["sshkeys"] = quote(sshkeys)
# One key per line, URL-encoded without exception: Proxmox's
# "urlencoded" format refuses an unescaped "/" or "+".
cloud_init_args["sshkeys"] = quote("\n".join(ssh_public_keys), safe="")
self._node_api().qemu(vmid).config.post(**cloud_init_args)
@@ -819,16 +828,7 @@ class ProxmoxVMProvisionMixin:
snippets = self._cicustom_snippets(vmid_int)
# Step 2: Delete VM
# Proxmox's API parameter is hyphenated (destroy-unreferenced-disks),
# not a valid Python identifier — proxmoxer forwards kwargs to the
# request verbatim with no underscore-to-hyphen translation, so this
# must be built as a dict and unpacked rather than passed as a kwarg.
_logger.debug(f"Deleting VM {vmid} configuration and disks")
delete_params = {
"purge": 1,
"destroy-unreferenced-disks": 1 if remove_disk else 0,
}
self._node_api().qemu(vmid_int).delete(**delete_params)
self._delete_vm(vmid_int, remove_disk, timeout)
# Step 3: Clean up Cloud-Init snippets
# (This is best-effort; snippet files may be unreachable if storage is unavailable)
@@ -845,6 +845,21 @@ class ProxmoxVMProvisionMixin:
_logger.exception(f"Failed to destroy VM {vmid}: {e}")
raise
def _delete_vm(self, vmid: int, remove_disk: bool, timeout: int) -> None:
"""Delete the VM and wait for it to be gone: the delete is a task."""
_logger.debug(f"Deleting VM {vmid} configuration and disks")
# Proxmox's API parameter is hyphenated (destroy-unreferenced-disks),
# not a valid Python identifier — proxmoxer forwards kwargs to the
# request verbatim with no underscore-to-hyphen translation, so this
# must be built as a dict and unpacked rather than passed as a kwarg.
delete_params = {
"purge": 1,
"destroy-unreferenced-disks": 1 if remove_disk else 0,
}
upid = self._node_api().qemu(vmid).delete(**delete_params)
if upid:
self._wait_for_task(upid, timeout=timeout)
def _cicustom_snippets(self, vmid: int) -> list[tuple[str, str]]:
"""``(storage, path)`` of every snippet the VM's cicustom names.