feat: ignore switch VLANs and remember VLAN decisions per profile

- New "ignore" choice: the VLAN is neither created nor assigned and is left
  out of interface labels and the VLAN column
- VLAN decisions are stored once per profile and shared by all switches;
  per-switch decisions from 4.5.0 are migrated on load
- Review dialog shows one row per VID; only open VLANs are listed, stored and
  unambiguous ones sit in a collapsed, editable section

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-30 14:33:14 +01:00
1 parent f729473b64
commit 3df4e6a9fc
7 files changed
+178 -63

No files matched your search

+5 -1
View File
@@ -68,7 +68,11 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
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
and the switch's tenant). VLANs can also be **ignored** on all switches –
they are neither created nor assigned and are left out of the labels. VLAN
decisions are stored per profile (shared by all its switches); only VLANs
that still need a decision are shown, stored and unambiguous ones are in a
collapsed section that can be expanded for editing. 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
+9
View File
@@ -116,6 +116,8 @@ def empty_profile(name):
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
"cluster_map": {},
"host_map": {},
# Switch VLAN decisions for all switches: "<vid>" -> {"action": "map"|"new"|"skip"|"ignore", ...}.
"vlan_map": {},
# Windows client scan: targets and options, never a password.
"clients": dict(DEFAULT_CLIENT_OPTIONS),
}
@@ -164,6 +166,7 @@ class ProfileStore:
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"cluster_map": dict(record.get("cluster_map", {})),
"host_map": dict(record.get("host_map", {})),
"vlan_map": dict(record.get("vlan_map", {})),
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
if key in DEFAULT_CLIENT_OPTIONS}},
})
@@ -171,6 +174,11 @@ class ProfileStore:
profile["sources"].append(self._decrypt_record(source, f"{name}: {source.get('name', 'Quelle')}"))
for switch in record.get("switches", []):
profile["switches"].append(self._decrypt_record(switch, f"{name}: {switch.get('name', 'Switch')}"))
# Migration from 4.5: VLAN decisions were stored per switch.
for switch in profile["switches"]:
for vid, choice in (switch.pop("vlan_map", None) or {}).items():
profile["vlan_map"].setdefault(vid, choice)
switch.pop("create_vlans", None)
# Migration from v2: one VMware source embedded in each profile.
if not profile["sources"] and record.get("esxi_host"):
@@ -228,6 +236,7 @@ class ProfileStore:
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
"cluster_map": dict(profile.get("cluster_map", {})),
"host_map": dict(profile.get("host_map", {})),
"vlan_map": dict(profile.get("vlan_map", {})),
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
})
+24 -6
View File
@@ -1075,9 +1075,23 @@ VLAN_METHODS = {
"manual": "manuell",
"new": "fehlt",
"skip": "nicht zuordnen",
"ignore": "ignoriert",
}
def ignored_vlans(vlan_map):
"""VLAN IDs the user chose to ignore on all switches of the profile."""
return {int(vid) for vid, choice in (vlan_map or {}).items() if (choice or {}).get("action") == "ignore"}
def without_vlans(vlans, ignored):
"""Port VLAN membership without ignored VLANs (``None`` stays ``None``)."""
if not vlans or not ignored:
return vlans
return dict(vlans, untagged=[vid for vid in vlans.get("untagged", []) if vid not in ignored],
tagged=[vid for vid in vlans.get("tagged", []) if vid not in ignored])
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."""
@@ -1134,8 +1148,8 @@ def match_vlans(vids, names, vlans, tenant_id, site_id, manual=None):
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)
if choice.get("action") in ("skip", "ignore"):
result[vid] = (None, choice["action"], switch_name)
continue
if choice.get("action") == "map" and choice.get("id") in by_id:
result[vid] = (by_id[choice["id"]], "manual", switch_name)
@@ -1225,6 +1239,7 @@ def plan_switch_sync(nb, config, snapshot):
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,
"stored": str(vid) in vlan_map,
"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)}
@@ -1236,7 +1251,8 @@ def plan_switch_sync(nb, config, snapshot):
"device": {"id": device.id, "name": device.name},
"interfaces": [
{"name": item["name"], "netbox_name": record.name if record else "", "method": method,
"physical": _physical_interface(item), "vlan_label": vlan_label(item.get("vlans"))}
"physical": _physical_interface(item),
"vlan_label": vlan_label(without_vlans(item.get("vlans"), ignored_vlans(vlan_map)))}
for item in snapshot["interfaces"]
for record, method in [matches[item["name"]]]
],
@@ -1425,6 +1441,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report)
_sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report)
vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report)
ignored = ignored_vlans(config.get("vlan_map"))
matches = match_interfaces(snapshot["interfaces"], list(nb.dcim.interfaces.filter(device_id=device_id)),
config.get("interface_map"))
records = {}
@@ -1432,7 +1449,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
for interface in snapshot["interfaces"]:
key = interface_key(interface["name"])
record, method = matches[interface["name"]]
label = vlan_label(interface.get("vlans"))
port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored))
label = vlan_label(port["vlans"])
try:
if record:
changes = {}
@@ -1442,7 +1460,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
# routed ports and snapshots without configuration.
if label and (getattr(record, "label", "") or "") != label:
changes["label"] = label
changes.update(_vlan_assignment(interface, vlan_ids, record))
changes.update(_vlan_assignment(port, vlan_ids, record))
if changes:
report["interfaces_updated"] += 1
texts = []
@@ -1467,7 +1485,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
}
if label:
payload["label"] = label
payload.update(_vlan_assignment(interface, vlan_ids))
payload.update(_vlan_assignment(port, vlan_ids))
if interface.get("description"):
payload["description"] = interface["description"][:200]
report["interfaces_created"] += 1
+8 -2
View File
@@ -405,7 +405,9 @@ class Actions:
if not self.require_netbox_config():
return
by_id = {switch["id"]: switch for switch in self.state.switches}
items = [(dict(by_id[switch_id]), self.state.switch_snapshots[switch_id])
# VLAN decisions are shared by all switches of the profile.
vlan_map = self.state.profile.setdefault("vlan_map", {})
items = [(dict(by_id[switch_id], vlan_map=dict(vlan_map)), self.state.switch_snapshots[switch_id])
for switch_id in switch_ids if switch_id in by_id and switch_id in self.state.switch_snapshots]
if not items:
widgets.message(self.window, "Keine Daten", "Bitte die Switche zuerst auslesen.", "info")
@@ -429,7 +431,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(vlan["method"] != "vid" for vlan in item["vlans"])
or item["networks"] or any(not vlan["stored"] and vlan["method"] in ("new", "ambiguous") for vlan in item["vlans"])
for _switch, item in reviewable)
def ask():
@@ -440,13 +442,17 @@ class Actions:
if not dialog.exec():
return
stored = {switch["id"]: switch for switch in self.state.switches}
vlan_map.clear()
vlan_map.update(dialog.vlan_map)
for switch, _snapshot in items:
choices = dialog.result.get(switch["id"])
if choices:
switch.update(choices)
if switch["id"] in stored:
stored[switch["id"]].update(choices)
switch["vlan_map"] = dict(vlan_map)
self.state.touch()
self.state.switches_changed.emit() # ignored VLANs vanish from the VLAN column
self.tasks.run(lambda ctx: preview(ctx, nb), title="Änderungen berechnen", area="switch",
on_success=show_preview, on_error=self._netbox_failed)
QTimer.singleShot(0, ask)
+100 -52
View File
@@ -590,6 +590,9 @@ class SwitchMappingDialog(_Dialog):
self.resize(1120, 680)
self.plans = plans
self.result = None
# Profile-wide VLAN decisions; every switch config carries the same map.
self.previous_vlan_map = dict((plans[0][0].get("vlan_map") if plans else None) or {})
self.vlan_map = dict(self.previous_vlan_map)
tabs = QTabWidget()
# Interfaces --------------------------------------------------------
@@ -699,59 +702,46 @@ class SwitchMappingDialog(_Dialog):
tabs.addTab(network_page, f"Netze ({missing} Prefix(e) fehlen)")
# VLANs -----------------------------------------------------------------
# VLAN decisions apply to all switches of the profile: one row per VID.
self.vlan_rows = []
vlans = [(switch, plan, item) for switch, plan in plans for item in plan["vlans"]]
if vlans:
merged = {}
for switch, plan in plans:
for item in plan["vlans"]:
entry = merged.setdefault(item["vid"], {"item": item, "switches": [], "candidates": {}, "tenants": {}})
entry["switches"].append(switch["name"])
entry["candidates"].update({candidate["id"]: candidate["label"] for candidate in item["candidates"]})
entry["tenants"].update({tenant["id"]: tenant["name"] for tenant in plan["tenants"]})
if merged:
vlan_page = QWidget()
vlan_layout = QVBoxLayout(vlan_page)
vlan_layout.setContentsMargins(0, 12, 0, 0)
vlan_layout.addWidget(label(
"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, 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"], str(item["vid"]), item["name"])):
self.vlan_table.setItem(row, column, QTableWidgetItem(text))
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, *_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 ")"))
"Gesucht wird in der Mandantengruppe über die VLAN-ID; bei mehreren Treffern entscheiden Mandant, "
"Standort und Name. Neue VLANs erhalten den eingetragenen Namen und Mandanten. Ignorierte VLANs "
"werden weder angelegt noch zugeordnet und fehlen im Label. Die Auswahl gilt für alle Switche "
"des Profils und wird gespeichert.", muted=True, wrap=True))
settled = {vid: entry["item"]["stored"] or entry["item"]["method"] in ("vid", "name")
for vid, entry in merged.items()}
open_count = sum(1 for value in settled.values() if not value)
self.open_vlan_table = self._vlan_table()
self.settled_vlan_table = self._vlan_table()
for vid in sorted(merged):
self._add_vlan_row(self.settled_vlan_table if settled[vid] else self.open_vlan_table, merged[vid])
for table in (self.open_vlan_table, self.settled_vlan_table):
self._prepare_table(table, (130, 60, 150, 280, 190, 170, 110))
vlan_layout.addWidget(label(f"<b>Zu prüfen ({open_count})</b>" if open_count else
"Alle VLANs sind zugeordnet oder gespeichert.", wrap=True))
vlan_layout.addWidget(self.open_vlan_table, 1)
self.open_vlan_table.setVisible(bool(open_count))
self.settled_toggle = button("", variant="link")
self.settled_toggle.setCheckable(True)
self.settled_toggle.toggled.connect(self._toggle_settled)
vlan_layout.addWidget(self.settled_toggle, 0, Qt.AlignLeft)
vlan_layout.addWidget(self.settled_vlan_table, 1)
self._settled_count = len(merged) - open_count
self._toggle_settled(False)
missing = sum(1 for entry in merged.values() if entry["item"]["method"] == "new")
tabs.addTab(vlan_page, f"VLANs ({open_count} zu prüfen, {missing} fehlen)")
self.root.addWidget(tabs, 1)
self.root.addWidget(self.error_banner)
@@ -772,6 +762,60 @@ class SwitchMappingDialog(_Dialog):
for column, width in enumerate(widths):
table.setColumnWidth(column, width)
IGNORE = "\x00ignore"
@staticmethod
def _vlan_table():
table = QTableWidget(0, 7)
table.setHorizontalHeaderLabels(["Switch(e)", "VLAN", "Name (Switch)", "NetBox-VLAN",
"Name des neuen VLANs", "Mandant (neu)", "Zuordnung"])
return table
def _add_vlan_row(self, table, entry):
item = entry["item"]
row = table.rowCount()
table.insertRow(row)
switches = ", ".join(entry["switches"])
for column, text in enumerate((switches, str(item["vid"]), item["name"])):
table.setItem(row, column, QTableWidgetItem(text))
combo = QComboBox()
for candidate_id, text in sorted(entry["candidates"].items(), key=lambda pair: pair[1].casefold()):
combo.addItem(text, candidate_id)
combo.addItem("+ neu anlegen", self.NEW)
combo.addItem("– nicht zuordnen –", 0)
combo.addItem("⊘ ignorieren (auf allen Switchen)", self.IGNORE)
current = {"skip": 0, "ignore": self.IGNORE}.get(item["method"], item["netbox_id"] or self.NEW)
combo.setCurrentIndex(max(0, combo.findData(current)))
name = QLineEdit(item["new_name"])
name.setMaxLength(64)
name.setPlaceholderText(item["name"])
tenant = QComboBox()
for tenant_id, text in sorted(entry["tenants"].items(), key=lambda pair: pair[1].casefold()):
tenant.addItem(text, tenant_id)
tenant.setCurrentIndex(max(0, tenant.findData(item["new_tenant"])))
method = QTableWidgetItem(VLAN_METHODS.get(item["method"], item["method"])
+ (" · gespeichert" if item["stored"] else ""))
if not item["stored"] and item["method"] in ("ambiguous", "new"):
method.setForeground(QColor(theme.color("warning")))
table.setCellWidget(row, 3, combo)
table.setCellWidget(row, 4, name)
table.setCellWidget(row, 5, tenant)
table.setItem(row, 6, method)
def toggle(_index=None):
for widget in (name, tenant):
widget.setEnabled(combo.currentData() == self.NEW)
combo.currentIndexChanged.connect(toggle)
toggle()
self.vlan_rows.append((item, combo, name, tenant))
def _toggle_settled(self, expanded):
arrow = "▾" if expanded else "▸"
self.settled_toggle.setText(f"{arrow} Gespeicherte und eindeutig zugeordnete VLANs ({self._settled_count})"
+ ("" if expanded else " – zum Bearbeiten ausklappen"))
self.settled_vlan_table.setVisible(expanded and self._settled_count > 0)
self.settled_toggle.setVisible(self._settled_count > 0)
def _vrf_chosen(self, entry):
_row, switch, _item, combo, _status = entry
if combo.currentData() == self.NEW:
@@ -835,24 +879,28 @@ 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": [], "vlan_map": {}})
result[switch["id"]].update({"network_vrfs": {}, "create_prefixes": [], "create_vlans": []})
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, combo, name, tenant in self.vlan_rows:
vlan_map = dict(self.previous_vlan_map)
for 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.")
self.show_error(f"Bitte einen Namen für das neue VLAN {item['vid']} eingeben.")
return
choice = {"action": "new", "name": name.text().strip(), "tenant": tenant.currentData()}
elif chosen == self.IGNORE:
choice = {"action": "ignore"}
elif chosen:
choice = {"action": "map", "id": chosen}
else:
choice = {"action": "skip"}
result[switch["id"]]["vlan_map"][str(item["vid"])] = choice
vlan_map[str(item["vid"])] = choice
self.vlan_map = vlan_map
self.result = result
super().accept()
+3 -2
View File
@@ -4,7 +4,7 @@ import uuid
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHBoxLayout, QMenu, QSplitter, QStackedWidget
from netbox_sync.core.switches import PLATFORMS, vlan_label
from netbox_sync.core.switches import PLATFORMS, ignored_vlans, vlan_label, without_vlans
from netbox_sync.ui import widgets
from netbox_sync.ui.dialogs import AddSwitchesDialog, RawDataDialog, SwitchDialog
from netbox_sync.ui.icons import icon
@@ -108,7 +108,8 @@ class SwitchesPage(Page):
dot=lambda row: "success" if row["connected"] else ("text_faint" if row["enabled"] else "danger")),
Column("speed", "Geschwindigkeit", 115, value=lambda row: _speed(row.get("speed_mbps")),
sort=lambda row: row.get("speed_mbps") or 0),
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(row.get("vlans"))),
Column("vlans", "VLANs", 110, value=lambda row: vlan_label(without_vlans(
row.get("vlans"), ignored_vlans((self.state.profile or {}).get("vlan_map"))))),
Column("ips", "IP-Adressen", 160, value=lambda row: ", ".join(row.get("ip_addresses", []))),
Column("neighbor", "Nachbar", 170, value=lambda row: (row.get("neighbor") or {}).get("system_name", "")),
Column("remote_port", "Nachbar-Port", 110, value=lambda row: (row.get("neighbor") or {}).get("remote_port", "")),
+29
View File
@@ -213,3 +213,32 @@ def test_new_vlan_can_get_another_tenant_of_the_group():
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"
def test_ignored_vlans_are_left_out_everywhere():
nb, switch, snapshot = _numbered_setup()
nb.ipam.vlans.records.append(Record(nb.ipam.vlans, id=110, vid=10, name="Server", tenant=SimpleNamespace(id=7)))
snapshot["interfaces"][0]["vlans"] = {"untagged": [10], "tagged": [20, 30], "tagged_all": False}
switch["vlan_map"] = {"20": {"action": "ignore"}, "30": {"action": "new", "name": "Drucker"}}
plan = plan_switch_sync(nb, switch, snapshot)
by_vid = {item["vid"]: item for item in plan["vlans"]}
assert (by_vid[20]["method"], by_vid[20]["stored"]) == ("ignore", True)
assert by_vid[10]["stored"] is False
assert {item["name"]: item["vlan_label"] for item in plan["interfaces"]}["1/1/1"] == "10,30"
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
assert report["errors"] == []
assert [payload["vid"] for payload in nb.ipam.vlans.created] == [30]
port = nb.dcim.interfaces.get(1)
assert port.label == "10,30" and port.tagged_vlans == [nb.ipam.vlans.records[-1].id]
def test_vlan_decisions_move_from_switches_to_the_profile(tmp_path):
from netbox_sync.core.config import ProfileStore
store = ProfileStore(tmp_path / "config.json")
profile = {"name": "Kunde", "switches": [{"id": "s", "name": "sw", "password": "x",
"vlan_map": {"5": {"action": "ignore"}}, "create_vlans": [6]}]}
store.save({"Kunde": profile}, "Kunde")
loaded = store.load()[0]["Kunde"]
assert loaded["vlan_map"] == {"5": {"action": "ignore"}}
assert "vlan_map" not in loaded["switches"][0] and "create_vlans" not in loaded["switches"][0]