Compare commits

...
2 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 f729473b64 chore: release 4.5.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:18:10 +01:00
MrBlakeandClaude Opus 5.5 29d3724a7f feat: map switch VLANs across the tenant group, custom name and tenant for new VLANs
- Match switch VLANs to NetBox VLANs of the switch's tenant group by VID;
  own tenant, site and similar names decide between several candidates
- Review dialog: choose the NetBox VLAN per VID, skip it or create it with a
  custom name and a tenant of the tenant group
- Never create a VLAN twice when "create new" stays stored in the profile

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 14:18:09 +01:00
7 changed files with 234 additions and 51 deletions

No files matched your search

+7 -3
View File
@@ -63,9 +63,13 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
LLDP/CDP neighbour can be corrected; a neighbour can be assigned manually to
any device of the switch's tenant group. Choices are stored in the profile
- Networks and VLANs in the same review: per network the VRF (global, a tenant
VRF or a new one) and whether a missing prefix is created; missing VLANs
(named from the switch configuration) are only created when ticked. Existing
VLANs are assigned to the ports (802.1Q mode, untagged/tagged)
VRF or a new one) and whether a missing prefix is created
- VLAN mapping: switch VLANs are matched to NetBox VLANs of the switch's tenant
group by VID (own tenant, site and similar names decide between several);
each VLAN can be mapped manually, skipped or created with a name and a tenant
of the tenant group of your choice (pre-filled from the switch configuration
and the switch's tenant). Mapped VLANs are assigned
to the ports (802.1Q mode, untagged/tagged)
- Tenant required: a switch without tenant in NetBox is refused; every created
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer"
#ifndef AppVersion
#define AppVersion "4.4.0"
#define AppVersion "4.5.0"
#endif
#define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.4.0"
APP_VERSION = "4.5.0"
APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+124 -20
View File
@@ -1068,14 +1068,103 @@ def snapshot_vlan_ids(snapshot):
return sorted(vids)
def _tenant_vlans(nb, tenant_id, site_id):
"""``{VLAN ID: record}`` of the tenant; a VLAN of the switch's site wins."""
VLAN_METHODS = {
"vid": "gleiche VID",
"name": "VID + Name",
"ambiguous": "mehrdeutig",
"manual": "manuell",
"new": "fehlt",
"skip": "nicht zuordnen",
}
def candidate_vlans(nb, tenant_id):
"""VLANs of the switch's tenant group (or tenant) – a VLAN may belong to a
sibling tenant, e.g. a school network documented under its own tenant."""
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
found = {}
for vlan in nb.ipam.vlans.filter(tenant_id=tenant_id):
current = found.get(vlan.vid)
if current is None or (related_id(vlan, "site") == site_id and related_id(current, "site") != site_id):
found[vlan.vid] = vlan
return found
sources = [nb.ipam.vlans.filter(tenant_id=tenant_id)]
if group_id:
sources.append(nb.ipam.vlans.filter(tenant_group_id=group_id))
for source in sources:
for vlan in source:
found[vlan.id] = vlan
return list(found.values())
def candidate_tenants(nb, tenant_id):
"""Tenants a new VLAN may get: the tenant group of the switch's tenant."""
tenant = nb.tenancy.tenants.get(tenant_id)
group_id = related_id(tenant, "group") if tenant else None
tenants = {tenant_id: getattr(tenant, "name", None) or str(tenant_id)}
if group_id:
tenants.update({item.id: item.name for item in nb.tenancy.tenants.filter(group_id=group_id)})
return sorted(({"id": key, "name": value} for key, value in tenants.items()), key=lambda row: row["name"].casefold())
def _name_tokens(text):
return set(re.findall(r"[a-z]+|\d+", (text or "").casefold()))
def vlan_choice_label(vlan):
owner = getattr(getattr(vlan, "tenant", None), "name", None) or getattr(getattr(vlan, "group", None), "name", None)
return f"{vlan.vid} – {vlan.name}" + (f" ({owner})" if owner else "")
def match_vlans(vids, names, vlans, tenant_id, site_id, manual=None):
"""Assign NetBox VLANs to switch VLAN IDs.
Candidates need the same VID. With several, the own tenant, the switch's
site and similar names (``Server_LEO`` ↔ ``Leo Server``) decide.
``manual`` is ``{str(vid): {"action": "map"|"new"|"skip", "id", "name"}}``.
Returns ``{vid: (record or None, method, name for a new VLAN)}``.
"""
manual = manual or {}
by_vid, by_id = {}, {vlan.id: vlan for vlan in vlans}
for vlan in vlans:
by_vid.setdefault(vlan.vid, []).append(vlan)
result = {}
for vid in vids:
switch_name = names.get(vid) or f"VLAN{vid}"
choice = manual.get(str(vid)) or {}
if choice.get("action") == "new":
name = (choice.get("name") or switch_name)[:64]
# Created by an earlier run – use it instead of creating it again.
created = next((vlan for vlan in by_vid.get(vid, []) if vlan.name.casefold() == name.casefold()), None)
result[vid] = (created, "manual", name) if created else (None, "new", name)
continue
if choice.get("action") == "skip":
result[vid] = (None, "skip", switch_name)
continue
if choice.get("action") == "map" and choice.get("id") in by_id:
result[vid] = (by_id[choice["id"]], "manual", switch_name)
continue
candidates = by_vid.get(vid, [])
if not candidates:
result[vid] = (None, "new", switch_name)
continue
tokens = _name_tokens(switch_name)
def score(vlan):
other = _name_tokens(vlan.name)
similarity = len(tokens & other) / len(tokens | other) if tokens | other else 0
return ((related_id(vlan, "tenant") == tenant_id) * 4 + (related_id(vlan, "site") == site_id) * 2
+ similarity * 3)
ranked = sorted(candidates, key=score, reverse=True)
if len(ranked) == 1:
method = "vid"
else:
method = "name" if score(ranked[0]) > score(ranked[1]) else "ambiguous"
result[vid] = (ranked[0], method, switch_name)
return result
def _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id):
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
vlans = candidate_vlans(nb, tenant_id)
return vlans, match_vlans(snapshot_vlan_ids(snapshot), names, vlans, tenant_id, site_id, config.get("vlan_map"))
def plan_switch_sync(nb, config, snapshot):
@@ -1127,12 +1216,21 @@ def plan_switch_sync(nb, config, snapshot):
"create": create_prefixes is None or network in create_prefixes})
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
present = _tenant_vlans(nb, tenant_id, related_id(device, "site"))
create_vlans = config.get("create_vlans")
vlans = [{"vid": vid, "name": names.get(vid) or f"VLAN{vid}",
"netbox_name": present[vid].name if vid in present else None,
"create": create_vlans is None or vid in create_vlans}
for vid in snapshot_vlan_ids(snapshot)]
candidates, vlan_matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, related_id(device, "site"))
tenants = candidate_tenants(nb, tenant_id)
allowed = {row["id"] for row in tenants}
vlan_map = config.get("vlan_map") or {}
vlans = []
for vid, (record, method, new_name) in vlan_matches.items():
new_tenant = (vlan_map.get(str(vid)) or {}).get("tenant")
vlans.append({
"vid": vid, "name": names.get(vid) or f"VLAN{vid}", "method": method, "new_name": new_name,
"new_tenant": new_tenant if new_tenant in allowed else tenant_id,
"netbox_id": record.id if record else None,
"candidates": [{"id": vlan.id, "label": vlan_choice_label(vlan)}
for vlan in sorted(candidates, key=lambda item: (item.name or "").casefold())
if vlan.vid == vid],
})
return {
"error": None,
"device": {"id": device.id, "name": device.name},
@@ -1150,6 +1248,7 @@ def plan_switch_sync(nb, config, snapshot):
"vrfs": vrfs,
"networks": networks,
"vlans": vlans,
"tenants": tenants,
}
@@ -1242,17 +1341,22 @@ def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report):
def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report):
"""``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved."""
present = {vid: vlan.id for vid, vlan in _tenant_vlans(nb, tenant_id, site_id).items()}
approved = {int(vid) for vid in config.get("create_vlans") or []}
names = {int(key): value for key, value in (snapshot.get("vlan_names") or {}).items()}
for vid in snapshot_vlan_ids(snapshot):
if vid in present or vid not in approved:
_vlans, matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id)
approved = {int(vid) for vid, choice in (config.get("vlan_map") or {}).items() if choice.get("action") == "new"}
approved |= {int(vid) for vid in config.get("create_vlans") or []} # profiles of version 4.4.0
present = {}
for vid, (record, method, name) in matches.items():
if record is not None:
present[vid] = record.id
continue
if method != "new" or vid not in approved:
continue
name = (names.get(vid) or f"VLAN{vid}")[:64]
try:
report["vlans_created"] += 1
report["changes"].append(f"VLAN {vid} „{name}“ neu")
payload = {"vid": vid, "name": name, "status": "active", "tenant": tenant_id}
# A different tenant may be chosen per VLAN in the review dialog.
chosen_tenant = ((config.get("vlan_map") or {}).get(str(vid)) or {}).get("tenant") or tenant_id
payload = {"vid": vid, "name": name[:64], "status": "active", "tenant": chosen_tenant}
if site_id:
payload["site"] = site_id
present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id
+1 -1
View File
@@ -429,7 +429,7 @@ class Actions:
needs_review = any(
any(entry["method"] not in ("name", "new") or (entry["method"] == "new" and entry["physical"])
for entry in item["interfaces"]) or (create_cables and item["neighbors"])
or item["networks"] or any(not vlan["netbox_name"] for vlan in item["vlans"])
or item["networks"] or any(vlan["method"] != "vid" for vlan in item["vlans"])
for _switch, item in reviewable)
def ask():
+54 -22
View File
@@ -26,7 +26,7 @@ from PySide6.QtWidgets import (
)
from netbox_sync.core.config import known_hosts_path
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, forget_host_key
from netbox_sync.core.switches import MATCH_METHODS, PLATFORMS, VLAN_METHODS, forget_host_key
from netbox_sync.core.virtualization import test_source
from netbox_sync.ui.icons import icon
from netbox_sync.ui.models import Column, FilterProxy, RowTableModel
@@ -706,29 +706,52 @@ class SwitchMappingDialog(_Dialog):
vlan_layout = QVBoxLayout(vlan_page)
vlan_layout.setContentsMargins(0, 12, 0, 0)
vlan_layout.addWidget(label(
"VLANs der Switch-Ports. Vorhandene VLANs des Mandanten werden den Schnittstellen zugeordnet "
"(802.1Q-Modus, untagged/tagged). Fehlende VLANs werden nur angelegt, wenn sie angehakt sind.",
"VLANs der Switch-Ports. Gesucht wird in der Mandantengruppe des Switches über die VLAN-ID; bei "
"mehreren Treffern entscheiden Mandant, Standort und Name. Zugeordnete VLANs werden an den "
"Schnittstellen gesetzt (802.1Q-Modus, untagged/tagged). Neue VLANs erhalten den eingetragenen "
"Namen und den gewählten Mandanten aus der Mandantengruppe (vorbelegt: Mandant des Switches).",
muted=True, wrap=True))
self.vlan_table = QTableWidget(0, 5)
self.vlan_table.setHorizontalHeaderLabels(["Switch", "Mandant", "VLAN", "Name (Switch)", "In NetBox"])
self.vlan_table = QTableWidget(0, 7)
self.vlan_table.setHorizontalHeaderLabels(["Switch", "VLAN", "Name (Switch)", "NetBox-VLAN",
"Name des neuen VLANs", "Mandant (neu)", "Zuordnung"])
for switch, plan, item in vlans:
row = self.vlan_table.rowCount()
self.vlan_table.insertRow(row)
for column, text in enumerate((switch["name"], plan["tenant"], str(item["vid"]), item["name"])):
for column, text in enumerate((switch["name"], str(item["vid"]), item["name"])):
self.vlan_table.setItem(row, column, QTableWidgetItem(text))
status = QTableWidgetItem(item["netbox_name"] or "fehlt – anlegen")
if item["netbox_name"]:
status.setFlags(Qt.ItemIsEnabled)
else:
status.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
status.setCheckState(Qt.Checked if item["create"] else Qt.Unchecked)
status.setForeground(QColor(theme.color("warning")))
self.vlan_table.setItem(row, 4, status)
self.vlan_rows.append((switch, item, status))
self._prepare_table(self.vlan_table, (140, 140, 70, 200, 200))
combo = QComboBox()
for candidate in item["candidates"]:
combo.addItem(candidate["label"], candidate["id"])
combo.addItem("+ neu anlegen", self.NEW)
combo.addItem("– nicht zuordnen –", 0)
current = item["netbox_id"] or (0 if item["method"] == "skip" else self.NEW)
combo.setCurrentIndex(max(0, combo.findData(current)))
name = QLineEdit(item["new_name"])
name.setMaxLength(64)
name.setPlaceholderText(item["name"])
method = QTableWidgetItem(VLAN_METHODS.get(item["method"], item["method"]))
if item["method"] in ("ambiguous", "new"):
method.setForeground(QColor(theme.color("warning")))
tenant = QComboBox()
for option in plan["tenants"]:
tenant.addItem(option["name"], option["id"])
tenant.setCurrentIndex(max(0, tenant.findData(item["new_tenant"])))
self.vlan_table.setCellWidget(row, 3, combo)
self.vlan_table.setCellWidget(row, 4, name)
self.vlan_table.setCellWidget(row, 5, tenant)
self.vlan_table.setItem(row, 6, method)
def toggle(_index=None, combo=combo, name=name, tenant=tenant):
for widget in (name, tenant):
widget.setEnabled(combo.currentData() == self.NEW)
combo.currentIndexChanged.connect(toggle)
toggle()
self.vlan_rows.append((switch, item, combo, name, tenant))
self._prepare_table(self.vlan_table, (130, 60, 150, 280, 200, 180, 110))
vlan_layout.addWidget(self.vlan_table, 1)
missing = sum(1 for _switch, item, _status in self.vlan_rows if not item["netbox_name"])
tabs.addTab(vlan_page, f"VLANs ({missing} fehlen)")
missing = sum(1 for _switch, item, *_widgets in self.vlan_rows if item["method"] == "new")
unclear = sum(1 for _switch, item, *_widgets in self.vlan_rows if item["method"] == "ambiguous")
tabs.addTab(vlan_page, f"VLANs ({missing} fehlen" + (f", {unclear} mehrdeutig)" if unclear else ")"))
self.root.addWidget(tabs, 1)
self.root.addWidget(self.error_banner)
@@ -812,15 +835,24 @@ class SwitchMappingDialog(_Dialog):
else:
stored[neighbor["local_port"]] = chosen
for switch, plan in self.plans:
result[switch["id"]].update({"network_vrfs": {}, "create_prefixes": [], "create_vlans": []})
result[switch["id"]].update({"network_vrfs": {}, "create_prefixes": [], "create_vlans": [], "vlan_map": {}})
for _row, switch, item, combo, status in self.network_rows:
choices = result[switch["id"]]
choices["network_vrfs"][item["network"]] = combo.currentData()
if status.data(Qt.CheckStateRole) is not None and status.checkState() == Qt.Checked:
choices["create_prefixes"].append(item["network"])
for switch, item, status in self.vlan_rows:
if not item["netbox_name"] and status.checkState() == Qt.Checked:
result[switch["id"]]["create_vlans"].append(item["vid"])
for switch, item, combo, name, tenant in self.vlan_rows:
chosen = combo.currentData()
if chosen == self.NEW:
if not name.text().strip():
self.show_error(f"{switch['name']}: Bitte einen Namen für das neue VLAN {item['vid']} eingeben.")
return
choice = {"action": "new", "name": name.text().strip(), "tenant": tenant.currentData()}
elif chosen:
choice = {"action": "map", "id": chosen}
else:
choice = {"action": "skip"}
result[switch["id"]]["vlan_map"][str(item["vid"])] = choice
self.result = result
super().accept()
+46 -3
View File
@@ -134,8 +134,8 @@ def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
snapshot["vlan_names"] = {20: "Clients"}
plan = plan_switch_sync(nb, switch, snapshot)
assert [(item["vid"], item["netbox_name"], item["name"]) for item in plan["vlans"]] == [
(1, None, "VLAN1"), (10, "Server", "VLAN10"), (20, None, "Clients")]
assert [(item["vid"], item["netbox_id"], item["method"], item["new_name"]) for item in plan["vlans"]] == [
(1, None, "new", "VLAN1"), (10, 110, "vid", "VLAN10"), (20, None, "new", "Clients")]
assert plan["networks"] == [{"network": "10.1.0.0/24", "vrf": "", "existing_vrfs": [], "create": True}]
# Not approved: nothing is created, only the existing VLAN 10 is assigned.
@@ -146,7 +146,7 @@ def test_missing_vlans_prefixes_and_vrfs_are_only_created_when_approved():
assert nb.dcim.interfaces.get(1).untagged_vlan == 110 and nb.dcim.interfaces.get(1).mode == "access"
assert nb.ipam.ip_addresses.created[0]["tenant"] == 7 and nb.ipam.ip_addresses.created[0]["vrf"] is None
switch.update({"create_vlans": [20], "create_prefixes": ["10.1.0.0/24"],
switch.update({"vlan_map": {"20": {"action": "new", "name": "Clients"}}, "create_prefixes": ["10.1.0.0/24"],
"network_vrfs": {"10.1.0.0/24": "Kunde-Mgmt"}})
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
@@ -170,3 +170,46 @@ def test_vlan_names_are_parsed():
from netbox_sync.core.switches import parse_vlan_names
assert parse_vlan_names('vlan 10\n name "Server"\n exit\nvlan 20\n name Clients\n#\n') == {
10: "Server", 20: "Clients"}
def test_vlans_of_sibling_tenants_are_matched_by_vid_and_name():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
leo = SimpleNamespace(id=8, name="Leo")
nb.ipam.vlans.records += [
Record(nb.ipam.vlans, id=201, vid=2, name="Leo Server", tenant=leo, tenant_group=group),
Record(nb.ipam.vlans, id=202, vid=2, name="Gast", tenant=SimpleNamespace(id=9), tenant_group=group),
Record(nb.ipam.vlans, id=230, vid=30, name="Fremd", tenant=SimpleNamespace(id=99), tenant_group=None),
]
snapshot["interfaces"][0]["vlans"] = {"untagged": [2], "tagged": [], "tagged_all": False}
snapshot["vlan_names"] = {2: "Server_LEO", 30: "Drucker"}
plan = plan_switch_sync(nb, switch, snapshot)
by_vid = {item["vid"]: item for item in plan["vlans"]}
assert (by_vid[2]["netbox_id"], by_vid[2]["method"]) == (201, "name")
assert [candidate["id"] for candidate in by_vid[2]["candidates"]] == [202, 201]
assert by_vid[30]["method"] == "new", "VLANs outside the tenant group are never used"
switch["vlan_map"] = {"30": {"action": "new", "name": "Drucker-Netz"}, "20": {"action": "skip"}}
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert nb.ipam.vlans.created == [{"vid": 30, "name": "Drucker-Netz", "status": "active", "tenant": 7}]
assert nb.dcim.interfaces.get(1).untagged_vlan == 201
assert getattr(nb.dcim.interfaces.get(2), "mode", None) is None, "skipped VLAN leaves the port alone"
def test_new_vlan_can_get_another_tenant_of_the_group():
nb, switch, snapshot = _numbered_setup()
group = SimpleNamespace(id=3, name="Kunde")
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=8, name="Leo", group=group))
nb.tenancy.tenants.records.append(Record(nb.tenancy.tenants, id=9, name="Fremd", group=None))
plan = plan_switch_sync(nb, switch, snapshot)
assert [row["name"] for row in plan["tenants"]] == ["Leo", "Muster"]
assert {item["new_tenant"] for item in plan["vlans"]} == {7}
switch["vlan_map"] = {"10": {"action": "new", "name": "Leo Server", "tenant": 8}}
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert nb.ipam.vlans.created == [{"vid": 10, "name": "Leo Server", "status": "active", "tenant": 8}]
# NetBox resolves the tenant group through the tenant; the fake needs it set.
nb.ipam.vlans.records[-1].tenant_group = group
again = plan_switch_sync(nb, switch, snapshot)["vlans"][0]
assert (again["netbox_id"], again["method"]) == (nb.ipam.vlans.records[-1].id, "manual"), "never created twice"