fix(hostname): rename only the node's own names in /etc/hosts

The rename replaced \b<old>\b, which also matches before "." and "-":
"pve.old.lan pve" became "new.dom.old.lan new.dom" and "pve-backup"
became "new-backup". Whole whitespace-separated names are renamed now,
comments left alone.

The live move of /etc/pve/nodes/<old> the issue also asks about is not
changed here; it needs a decision on clustered nodes.

Refs #21
This commit is contained in:
Christian Manivong committed 2026-11-01 21:48:06 +01:00
1 parent 89c70d85be
commit 8f10bef7c5
4 files changed
+101 -12

No files matched your search

+3
View File
@@ -51,6 +51,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `get_lldp_neighbors()` lists every neighbour of a port: a second neighbour on
the same port no longer overwrites the first, and a neighbour that sends no
system name is listed with an empty `hostname` instead of being dropped (#22).
- `set_hostname()` renames only the node's own names in `/etc/hosts`: other
hosts whose names start with the old one (`pve-backup`) and comments stay as
they are, and the old FQDN becomes the new one instead of a mix of both (#21).
## [0.8.0] - 2026-10-23
+25 -11
View File
@@ -49,6 +49,30 @@ _SNMP_WORD = re.compile(r'^[^\s"#]+$')
_SNMPD_CONF = "/etc/snmp/snmpd.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)
def _net(value: str) -> str:
return str(ipaddress.ip_network(value.strip(), strict=False))
@@ -633,17 +657,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"
+1 -1
View File
@@ -36,7 +36,7 @@
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_disk_smart": 74,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_packages": 66,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.get_users": 51,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 124,
"napalm_proxmox/system_mixin.py::ProxmoxSystemMixin.set_hostname": 114,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 179,
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin._download_cloud_image": 61,
+72
View File
@@ -0,0 +1,72 @@
"""set_hostname: what it writes to /etc/hosts (napalm-proxmox#21)."""
from __future__ import annotations
import base64
import re
import pytest
from napalm_proxmox import ProxmoxDriver
HOSTS = """\
127.0.0.1 localhost.localdomain localhost
# pve is the node; pve-backup its backup target
10.0.0.1 pve.old.lan pve
10.0.0.2 pve-backup.old.lan pve-backup
"""
class _Node:
"""The node's shell: /etc/hostname reads "pve", /etc/hosts reads HOSTS."""
def __init__(self) -> None:
self.ran: list[str] = []
def __call__(self, command: str) -> str:
self.ran.append(command)
if command.startswith("cat /etc/hostname"):
return "pve\n"
if command.startswith("cat /etc/hosts"):
return HOSTS
return ""
def written_hosts(self) -> str:
write = next(c for c in self.ran if c.rstrip().endswith("chmod 644 /etc/hosts"))
return base64.b64decode(re.match(r"echo (\S+) \| base64 -d", write).group(1)).decode()
@pytest.fixture
def node() -> _Node:
return _Node()
@pytest.fixture
def driver(node: _Node) -> ProxmoxDriver:
d = ProxmoxDriver("pve", "root@pam", "pw")
d._exec_ssh_command = node
return d
def test_an_fqdn_renames_the_nodes_names_and_nothing_else(driver, node):
driver.set_hostname("new.dom.lan")
assert node.written_hosts() == (
"127.0.0.1 localhost.localdomain localhost\n"
"# pve is the node; pve-backup its backup target\n"
"10.0.0.1 new.dom.lan new\n"
"10.0.0.2 pve-backup.old.lan pve-backup\n"
)
def test_a_short_name_keeps_the_old_domain(driver, node):
driver.set_hostname("new")
assert "10.0.0.1 new.old.lan new\n" in node.written_hosts()
assert "10.0.0.2 pve-backup.old.lan pve-backup\n" in node.written_hosts()
def test_the_same_name_leaves_hosts_alone(driver, node):
driver.set_hostname("pve")
assert not any("/etc/hosts" in c and "base64 -d" in c for c in node.ran)