Compare commits

..
3 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 773b3527db chore: release 4.2.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:35:23 +01:00
MrBlakeandClaude Opus 5.5 02f2d19e55 feat: map hypervisor hosts to NetBox devices during VM import
The import wizard asks for every ESXi host / Proxmox node which NetBox
device it corresponds to (names rarely match); the choice is remembered
per profile and set as the VM's device.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:35:17 +01:00
MrBlakeandClaude Opus 5.5 25dfa5e231 feat: export ESXi host / Proxmox node per VM in offline JSON
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:29:43 +01:00
8 changed files with 199 additions and 128 deletions

No files matched your search

+83 -119
View File
@@ -1,145 +1,109 @@
# NetBox Synchronizer # NetBox Synchronizer
Windows desktop application that documents virtual machines from VMware Windows-Desktopanwendung, die virtuelle Maschinen aus VMware vSphere und Proxmox VE, HPE-/Aruba-Switche
vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox. sowie Windows-Clients in NetBox dokumentiert.
| | |
|---|---|
| **Type** | Desktop application (Python, PySide6) |
| **Platform** | Windows |
| **Repository** | <https://git.mrblake.cc/MrBlake/NetBox-VM-Import-Desktop> |
## Features
### General
- Customer profiles with NetBox target, virtualisation sources and switch
credentials; switch between them in the sidebar
- Automatic saving; passwords, tokens and secrets are encrypted with Windows DPAPI
- All network access runs in the background — the window stays responsive and
operations can be cancelled
- Light and dark theme (optionally following Windows)
- Log with filter, search and export, plus a rotating log file under
`%APPDATA%\NetBox VM Import\logs`
- Keyboard shortcuts: `Ctrl+1…8` navigation, `F5` reload/read, `Ctrl+F` search
### Virtual machines
- Multiple VMware and Proxmox sources per profile, read in parallel; connection
test directly in the dialog
- QEMU/KVM VMs and optionally LXC containers; IP addresses via VMware Tools or
the QEMU guest agent
- Table with search, filters (source, status, "new"/"already in NetBox") and
multi-selection
- Automatic cluster mapping: each vCenter/ESXi or Proxmox cluster is mapped to
the NetBox cluster with the same (or a uniquely similar) name; manual
mappings are remembered in the profile, and missing clusters can be created in
NetBox directly
- Four-step import wizard: **Target** (cluster mapping, tenant preselected from
the cluster, VRF or global) → **Networks** (check missing prefixes with size
and VRF, create new VRFs directly) → **Review** (summary of all changes) →
**Import** (progress, live log, cancel)
- VMs are matched uniquely per cluster; existing prefixes are reused
- MAC addresses are set correctly on NetBox ≥ 4.2 (separate MAC model)
### Switches (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
- Add several NetBox devices in one step — host taken from the primary IP,
platform suggested from model/manufacturer
- Platform "detect automatically" via SSH
- Parallel SSH queries; SSH host keys are stored on first contact and verified
afterwards
- Interfaces, interface IP addresses and LLDP/CDP neighbours
- **Preview before writing**: all changes are computed as a dry run and only
sent after confirmation
- Interface types from device type templates are left untouched; Comware short
names (`GE1/0/1`) are mapped to full NetBox names (`GigabitEthernet1/0/1`)
- Cables from LLDP/CDP, also with FQDN system names or via the management IP
- The switch configuration is only changed when "Enable LLDP if needed" is
explicitly switched on
### Windows clients (agentless via WMI/CIM over WinRM)
- Targets from Active Directory (optional search OU, enabled accounts only,
last logon within N days, include/exclude servers) or as a list of host
names, IP addresses, networks (`192.0.2.0/24`) and ranges (`192.0.2.10-50`)
- Sign-in via the Windows credential dialog (domain account with local admin
rights, verified against the domain) or with the current Windows session; the
password is kept in memory only
- Reads name, manufacturer, model (for Lenovo the model name instead of the
machine type), serial number, form factor, operating system with
version/build, logged-on user, CPU/RAM and physical network adapters with MAC
and IPs
- Parallel queries; unreachable clients stay visible with their AD data, errors
come with a concrete hint
- Import as NetBox devices with site, role and tenant; manufacturers, device
types and platforms are created when needed, optionally interfaces, MAC and IP
addresses — with a preview before writing
- Built-in **setup guide**: group policy (WinRM, service, firewall),
permissions, common errors, check commands and a connection test for single
clients
### Offline mode (without NetBox)
- "Offline mode (without NetBox)" checkbox in the sidebar — global, independent
of the customer profile
- VMs and switches are read without a NetBox connection; switches can then be
added manually by name
- Selected VMs, clients or read switches are exported as a JSON file
(`*.nbsync.json`) — without passwords, tokens or user names
- On a machine with NetBox access, "Load from file …" (VMs, switches and
Windows clients pages) loads the file; the import wizard or dry-run preview
then runs as usual. Switches are matched by NetBox device ID or name
### VRFs & networks
- Create several VRFs or prefixes for one tenant at once
## Installation ## Installation
Run `NetBoxSynchronizer-Setup-<version>.exe`. The installer `NetBoxSynchronizer-Setup-<version>.exe` ausführen. Der Installer
- installs for the current user **without administrator rights** by default - installiert standardmäßig **ohne Administratorrechte** für den aktuellen Benutzer
("for all users" can be selected in the wizard), (im Assistenten kann „für alle Benutzer“ gewählt werden),
- creates a Start menu entry and optionally a desktop shortcut, - legt einen Startmenü-Eintrag und optional eine Desktop-Verknüpfung an,
- updates an existing installation in place, - aktualisiert eine vorhandene Installation direkt,
- asks on uninstall whether customer profiles and logs should be removed too. - fragt bei der Deinstallation, ob Kundenprofile und Protokolle ebenfalls gelöscht werden sollen.
Customer profiles of the predecessor ("NetBox VM Import") are migrated Bestehende Kundenprofile der Vorgängerversion („NetBox VM Import“) werden automatisch übernommen.
automatically.
## Development ## Funktionen
**Allgemein**
- Kundenprofile mit NetBox-Ziel, Virtualisierungsquellen und Switch-Zugängen; Wechsel über die Seitenleiste
- Automatisches Speichern; Passwörter, Tokens und Secrets mit Windows DPAPI verschlüsselt
- Alle Netzwerkzugriffe laufen im Hintergrund – das Fenster bleibt bedienbar, Vorgänge lassen sich abbrechen
- Helles und dunkles Design (folgt auf Wunsch Windows)
- Protokoll mit Filter, Suche und Export; zusätzlich rotierende Logdatei unter `%APPDATA%\NetBox VM Import\logs`
- Tastenkürzel: `Strg+1…8` Navigation, `F5` neu laden/auslesen, `Strg+F` Suche
**Virtuelle Maschinen**
- Mehrere VMware- und Proxmox-Quellen pro Profil, parallel ausgelesen; Verbindungstest direkt im Dialog
- QEMU/KVM-VMs und optional LXC-Container; IP-Adressen über VMware Tools bzw. QEMU Guest Agent
- Tabelle mit Suche, Filtern (Quelle, Status, „neu“/„bereits in NetBox“) und Mehrfachauswahl
- Automatische Cluster-Zuordnung: Jeder vCenter-/ESXi- bzw. Proxmox-Cluster wird dem gleichnamigen (oder eindeutig
ähnlichen) NetBox-Cluster zugeordnet; manuelle Zuordnungen merkt sich das Kundenprofil, fehlende Cluster können
direkt in NetBox angelegt werden
- Import-Assistent in vier Schritten: **Ziel** (Cluster-Zuordnung, Mandant aus dem Cluster vorausgewählt, VRF oder global)
→ **Netzwerke** (fehlende Präfixe mit Größe und VRF prüfen, neue VRFs direkt anlegen)
→ **Prüfen** (Zusammenfassung aller Änderungen) → **Import** (Fortschritt, Live-Protokoll, Abbrechen)
- VMs werden pro Cluster eindeutig zugeordnet; vorhandene Präfixe werden wiederverwendet
- MAC-Adressen werden auch mit NetBox ≥ 4.2 (eigenes MAC-Modell) korrekt gesetzt
**Switche** (Aruba CX, ArubaOS-Switch/ProCurve, HPE Comware)
- Mehrere NetBox-Geräte in einem Schritt hinzufügen – Host aus der primären IP, Plattform aus Modell/Hersteller vorgeschlagen
- Plattform „Automatisch erkennen“ per SSH
- Parallele SSH-Abfragen; SSH-Hostschlüssel werden beim ersten Kontakt gespeichert und danach geprüft
- Schnittstellen, Interface-IP-Adressen sowie LLDP-/CDP-Nachbarn
- **Vorschau vor dem Schreiben**: alle Änderungen werden als Dry-Run berechnet und erst nach Bestätigung übertragen
- Interface-Typen aus Gerätetyp-Vorlagen bleiben unangetastet; Comware-Kurznamen (`GE1/0/1`) werden den
vollständigen NetBox-Namen (`GigabitEthernet1/0/1`) zugeordnet
- Kabel aus LLDP/CDP auch bei FQDN-Systemnamen oder über die Management-IP
- Die Switch-Konfiguration wird nur verändert, wenn „LLDP bei Bedarf aktivieren“ ausdrücklich eingeschaltet ist
**Windows-Clients** (agentlos per WMI/CIM über WinRM)
- Ziele aus dem Active Directory (optional Such-OU, nur aktivierte Konten, letzte Anmeldung innerhalb von N Tagen,
Server ein-/ausschließen) oder als Liste von Hostnamen, IP-Adressen, Netzen (`10.0.10.0/24`) und Bereichen
(`10.0.20.10-50`)
- Anmeldung über das Windows-Anmeldefenster (Domänenkonto mit lokalen Adminrechten, wird gegen die Domäne geprüft)
oder mit der aktuellen Windows-Anmeldung; das Kennwort bleibt nur im Arbeitsspeicher
- Liest Name, Hersteller, Modell (bei Lenovo der Modellname statt des Maschinentyps), Seriennummer, Bauform,
Betriebssystem mit Version/Build, angemeldeten Benutzer, CPU/RAM sowie physische Netzwerkkarten mit MAC und IPs
- Parallele Abfrage; nicht erreichbare Clients bleiben mit den AD-Daten sichtbar, Fehler mit konkretem Hinweis
- Übernahme als NetBox-Geräte mit Standort, Rolle und Mandant; Hersteller, Gerätetypen und Plattformen werden bei
Bedarf angelegt, optional Schnittstellen, MAC- und IP-Adressen – mit Vorschau vor dem Schreiben
- **Einrichtungshilfe** im Programm: Gruppenrichtlinie (WinRM, Dienst, Firewall), Berechtigungen, Fehlerbilder,
Prüfbefehle und ein Verbindungstest für einzelne Clients
**Offline-Modus (ohne NetBox)**
- Checkbox „Offline-Modus (ohne NetBox)“ in der Seitenleiste – gilt global, unabhängig vom Kundenprofil
- VMs und Switche werden ohne NetBox-Verbindung ausgelesen; Switche lassen sich dann manuell per Name anlegen
- Ausgewählte VMs, Clients bzw. ausgelesene Switche werden als JSON-Datei (`*.nbsync.json`) exportiert – ohne Passwörter,
Tokens oder Benutzernamen
- Auf einem Rechner mit NetBox-Zugang lädt „Aus Datei laden …“ (Seiten VMs, Switche und Windows-Clients) die Datei; danach laufen
Import-Assistent bzw. Dry-Run-Vorschau wie gewohnt. Switche werden über NetBox-Geräte-ID oder Namen zugeordnet
**VRFs & Netze**
- Mehrere VRFs oder Präfixe für einen Mandanten gesammelt anlegen
## Entwicklung
```powershell ```powershell
py -3 -m venv .venv py -3 -m venv .venv
.\.venv\Scripts\Activate.ps1 .\.venv\Scripts\Activate.ps1
pip install -r requirements-dev.txt pip install -r requirements-dev.txt
python main.py # start the application python main.py # Anwendung starten
python -m pytest # tests python -m pytest # Tests
``` ```
Project layout: Projektstruktur:
``` ```
netbox_sync/ netbox_sync/
core/ UI-independent logic: configuration, NetBox, VMware/Proxmox, VM import, switches, Windows clients core/ UI-unabhängige Logik: Konfiguration, NetBox, VMware/Proxmox, VM-Import, Switche, Windows-Clients
ui/ Qt interface (PySide6): main window, pages, dialogs, import wizard, theme ui/ Qt-Oberfläche (PySide6): Hauptfenster, Seiten, Dialoge, Import-Assistent, Theme
resources/ icons resources/ Icons
installer/ Inno Setup script installer/ Inno-Setup-Skript
tests/ pytest (parsers, configuration, sync against an in-memory NetBox) tests/ pytest (Parser, Konfiguration, Sync gegen eine In-Memory-NetBox)
``` ```
## Build & installer ## Build & Installer
The installer requires [Inno Setup 6](https://jrsoftware.org/isinfo.php) Voraussetzung für den Installer ist [Inno Setup 6](https://jrsoftware.org/isinfo.php)
(`winget install JRSoftware.InnoSetup`). (`winget install JRSoftware.InnoSetup`).
```powershell ```powershell
.\build.ps1 # tests, PyInstaller build and installer .\build.ps1 # Tests, PyInstaller-Build und Installer
.\build.ps1 -SkipInstaller # only dist\NetBoxSynchronizer\ .\build.ps1 -SkipInstaller # nur dist\NetBoxSynchronizer\
``` ```
Output: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe` and the Ergebnis: `dist\installer\NetBoxSynchronizer-Setup-<version>.exe` sowie die portable Variante
portable variant `dist\portable\NetBox VM Import.exe` (runs without `dist\portable\NetBox VM Import.exe` (ohne Installation lauffähig; `-SkipPortable` lässt sie weg). Die Version steht in `netbox_sync/__init__.py`.
installation; `-SkipPortable` omits it). The version is set in
`netbox_sync/__init__.py`.
+1 -1
View File
@@ -3,7 +3,7 @@
#define AppName "NetBox Synchronizer" #define AppName "NetBox Synchronizer"
#ifndef AppVersion #ifndef AppVersion
#define AppVersion "4.1.1" #define AppVersion "4.2.0"
#endif #endif
#define AppPublisher "Louis-Alexander Kerst" #define AppPublisher "Louis-Alexander Kerst"
#define AppExeName "NetBoxSynchronizer.exe" #define AppExeName "NetBoxSynchronizer.exe"
+1 -1
View File
@@ -1,7 +1,7 @@
"""NetBox Synchronizer – VMs, switches and clients from the field into NetBox.""" """NetBox Synchronizer – VMs, switches and clients from the field into NetBox."""
APP_NAME = "NetBox Synchronizer" APP_NAME = "NetBox Synchronizer"
APP_VERSION = "4.1.1" APP_VERSION = "4.2.0"
APP_PUBLISHER = "Louis-Alexander Kerst" APP_PUBLISHER = "Louis-Alexander Kerst"
APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer" APP_USER_MODEL_ID = "Louis-AlexanderKerst.NetBoxSynchronizer"
+3
View File
@@ -115,6 +115,7 @@ def empty_profile(name):
"switches": [], "switches": [],
# Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name. # Remembered assignment "<source id>:<hypervisor cluster>" -> NetBox cluster name.
"cluster_map": {}, "cluster_map": {},
"host_map": {},
# Windows client scan: targets and options, never a password. # Windows client scan: targets and options, never a password.
"clients": dict(DEFAULT_CLIENT_OPTIONS), "clients": dict(DEFAULT_CLIENT_OPTIONS),
} }
@@ -162,6 +163,7 @@ class ProfileStore:
"netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"), "netbox_token": self._decrypt(record.get("netbox_token_encrypted", ""), f"{name}: NetBox-Token"),
"netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))), "netbox_ignore_ssl": bool(record.get("netbox_ignore_ssl", record.get("ignore_ssl_errors", False))),
"cluster_map": dict(record.get("cluster_map", {})), "cluster_map": dict(record.get("cluster_map", {})),
"host_map": dict(record.get("host_map", {})),
"clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items() "clients": {**DEFAULT_CLIENT_OPTIONS, **{key: value for key, value in record.get("clients", {}).items()
if key in DEFAULT_CLIENT_OPTIONS}}, if key in DEFAULT_CLIENT_OPTIONS}},
}) })
@@ -225,6 +227,7 @@ class ProfileStore:
"sources": [self._encrypt_record(source) for source in profile.get("sources", [])], "sources": [self._encrypt_record(source) for source in profile.get("sources", [])],
"switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])], "switches": [self._encrypt_record(switch) for switch in profile.get("switches", [])],
"cluster_map": dict(profile.get("cluster_map", {})), "cluster_map": dict(profile.get("cluster_map", {})),
"host_map": dict(profile.get("host_map", {})),
"clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)), "clients": dict(profile.get("clients", DEFAULT_CLIENT_OPTIONS)),
}) })
+1
View File
@@ -75,6 +75,7 @@ def validate(data):
raise ExchangeError("Die Datei enthält eine VM ohne Name oder Quelle.") raise ExchangeError("Die Datei enthält eine VM ohne Name oder Quelle.")
vm.setdefault("interfaces", []) vm.setdefault("interfaces", [])
vm.setdefault("cluster", "") vm.setdefault("cluster", "")
vm.setdefault("host", "")
vm.setdefault("status", "offline") vm.setdefault("status", "offline")
for key in ("vcpus", "memory", "disk"): for key in ("vcpus", "memory", "disk"):
vm[key] = int(vm.get(key) or 0) vm[key] = int(vm.get(key) or 0)
+4 -3
View File
@@ -87,7 +87,7 @@ def load_vmware_source(source, log=_noop):
if properties.get("name") and not properties.get("config.template"): if properties.get("name") and not properties.get("config.template"):
vm = _normalize_vmware_vm(properties, source, vim) vm = _normalize_vmware_vm(properties, source, vim)
host = properties.get("runtime.host") host = properties.get("runtime.host")
vm["cluster"] = host_clusters.get(getattr(host, "_moId", None), "") vm["cluster"], vm["host"] = host_clusters.get(getattr(host, "_moId", None), ("", ""))
normalized.append(vm) normalized.append(vm)
return normalized return normalized
finally: finally:
@@ -97,14 +97,14 @@ def load_vmware_source(source, log=_noop):
def _vmware_host_clusters(content, vim): def _vmware_host_clusters(content, vim):
"""Map ESXi host IDs to their cluster name (or the host name when standalone).""" """Map ESXi host IDs to ``(cluster name, host name)``; standalone hosts use their own name as cluster."""
result = {} result = {}
view = content.viewManager.CreateContainerView(content.rootFolder, [vim.ComputeResource], True) view = content.viewManager.CreateContainerView(content.rootFolder, [vim.ComputeResource], True)
try: try:
for resource in view.view: for resource in view.view:
name = resource.name name = resource.name
for host in resource.host or []: for host in resource.host or []:
result[host._moId] = name result[host._moId] = (name, host.name)
finally: finally:
view.Destroy() view.Destroy()
return result return result
@@ -205,6 +205,7 @@ def load_proxmox_source(source, log=_noop):
try: try:
guest = _normalize_proxmox_guest(session, source, resource) guest = _normalize_proxmox_guest(session, source, resource)
guest["cluster"] = cluster_name or resource.get("node", "") guest["cluster"] = cluster_name or resource.get("node", "")
guest["host"] = resource.get("node", "")
result.append(guest) result.append(guest)
except Exception as error: # noqa: BLE001 - one broken guest must not stop the source except Exception as error: # noqa: BLE001 - one broken guest must not stop the source
log(f"{source['name']} / VMID {resource.get('vmid')}: {error}", "warning") log(f"{source['name']} / VMID {resource.get('vmid')}: {error}", "warning")
+38 -2
View File
@@ -28,6 +28,11 @@ def cluster_key(vm):
return f"{vm.get('source_id', vm.get('source', ''))}:{vm.get('cluster', '')}" return f"{vm.get('source_id', vm.get('source', ''))}:{vm.get('cluster', '')}"
def host_key(vm):
"""Identifies the hypervisor host (ESXi host / Proxmox node) of a VM across sources."""
return f"{vm.get('source', '')}:{vm.get('host', '')}"
def _compact(name): def _compact(name):
return re.sub(r"[^0-9a-z]", "", (name or "").casefold()) return re.sub(r"[^0-9a-z]", "", (name or "").casefold())
@@ -60,6 +65,7 @@ class VMSyncEngine:
self.tenants = {} self.tenants = {}
self.vrfs = [] self.vrfs = []
self.platforms = [] self.platforms = []
self.devices = {}
self.existing_vms = {} self.existing_vms = {}
self._reset_run_state() self._reset_run_state()
@@ -86,12 +92,19 @@ class VMSyncEngine:
if tenant_id and tenant_name: if tenant_id and tenant_name:
self.cluster_tenants[cluster.name] = {"id": tenant_id, "name": tenant_name} self.cluster_tenants[cluster.name] = {"id": tenant_id, "name": tenant_name}
self.tenants.setdefault(tenant_name, tenant_id) self.tenants.setdefault(tenant_name, tenant_id)
self.devices = {}
for device in self.nb.dcim.devices.all():
if device.name:
self.devices[device.id] = {
"name": device.name, "site": related_name(device, "site") or "",
"cluster_id": related_id(device, "cluster"),
}
self.existing_vms = {} self.existing_vms = {}
for vm in self.nb.virtualization.virtual_machines.filter(brief=True): for vm in self.nb.virtualization.virtual_machines.filter(brief=True):
self.existing_vms.setdefault(vm.name, []).append(vm.id) self.existing_vms.setdefault(vm.name, []).append(vm.id)
self.log( self.log(
f"NetBox: {len(self.clusters)} Cluster, {len(self.tenants)} Mandanten, " f"NetBox: {len(self.clusters)} Cluster, {len(self.tenants)} Mandanten, "
f"{len(self.vrfs)} VRFs, {sum(map(len, self.existing_vms.values()))} VMs" f"{len(self.vrfs)} VRFs, {len(self.devices)} Geräte, {sum(map(len, self.existing_vms.values()))} VMs"
) )
def tenant_vrfs(self, tenant_id): def tenant_vrfs(self, tenant_id):
@@ -301,7 +314,28 @@ class VMSyncEngine:
raise RuntimeError(f"IP-Adresse {host_address} ist in dieser VRF mehrfach vorhanden") raise RuntimeError(f"IP-Adresse {host_address} ist in dieser VRF mehrfach vorhanden")
return candidates[0] if candidates else None return candidates[0] if candidates else None
def sync_vm(self, source_vm, cluster_id, tenant_id, vrf_id): def device_label(self, device_id):
device = self.devices[device_id]
return f"{device['name']} ({device['site']})" if device["site"] else device["name"]
def prepare_host_device(self, device_id, cluster_id):
"""Make sure the device may host VMs of the cluster; NetBox requires both to match.
A device without cluster is added to it. Returns ``False`` if it belongs to another cluster.
"""
device = self.devices[device_id]
if device["cluster_id"] == cluster_id:
return True
if device["cluster_id"]:
self.log(f"Gerät {device['name']} gehört in NetBox zu einem anderen Cluster – "
"wird nicht als Host eingetragen", "warning")
return False
self.nb.dcim.devices.get(device_id).update({"cluster": cluster_id})
device["cluster_id"] = cluster_id
self.log(f"Gerät {device['name']} dem Cluster zugeordnet", "success")
return True
def sync_vm(self, source_vm, cluster_id, tenant_id, vrf_id, device_id=None):
"""Create or update one VM. Returns ``"created"`` or ``"updated"``.""" """Create or update one VM. Returns ``"created"`` or ``"updated"``."""
payload = { payload = {
"name": source_vm["name"], "cluster": cluster_id, "status": source_vm["status"], "name": source_vm["name"], "cluster": cluster_id, "status": source_vm["status"],
@@ -311,6 +345,8 @@ class VMSyncEngine:
platform_id = self.get_platform_id(source_vm.get("guest_os")) platform_id = self.get_platform_id(source_vm.get("guest_os"))
if platform_id: if platform_id:
payload["platform"] = platform_id payload["platform"] = platform_id
if device_id and self.prepare_host_device(device_id, cluster_id):
payload["device"] = device_id
netbox_vm = self._find_vm(source_vm["name"], cluster_id) netbox_vm = self._find_vm(source_vm["name"], cluster_id)
if netbox_vm: if netbox_vm:
+68 -2
View File
@@ -22,7 +22,7 @@ from PySide6.QtWidgets import (
QWidget, QWidget,
) )
from netbox_sync.core.vm_sync import cluster_key, prefix_choices, vrf_label from netbox_sync.core.vm_sync import cluster_key, host_key, prefix_choices, vrf_label
from netbox_sync.ui.icons import icon from netbox_sync.ui.icons import icon
from netbox_sync.ui.tasks import log_bus from netbox_sync.ui.tasks import log_bus
from netbox_sync.ui.theme import theme from netbox_sync.ui.theme import theme
@@ -31,6 +31,7 @@ from netbox_sync.ui.widgets import Banner, SearchableComboBox, button, checkbox,
NEW_VRF = "__new__" NEW_VRF = "__new__"
NEW_CLUSTER = "__new_cluster__" NEW_CLUSTER = "__new_cluster__"
GLOBAL_VRF = "__global__" GLOBAL_VRF = "__global__"
NO_DEVICE = "__no_device__"
STEPS = ("Ziel", "Netzwerke", "Prüfen", "Import") STEPS = ("Ziel", "Netzwerke", "Prüfen", "Import")
@@ -127,6 +128,53 @@ class ImportWizard(QDialog):
group["vms"].append(vm) group["vms"].append(vm)
return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["cluster"].casefold())) return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["cluster"].casefold()))
def _host_groups(self):
groups = {}
for vm in self.vms:
if vm.get("host"):
key = host_key(vm)
groups.setdefault(key, {"key": key, "host": vm["host"], "source": vm.get("source", ""), "vms": []})
groups[key]["vms"].append(vm)
return sorted(groups.values(), key=lambda item: (item["source"].casefold(), item["host"].casefold()))
def _build_host_table(self):
"""Hypervisor host → NetBox device. Names rarely match, so the user always chooses."""
self.host_groups = self._host_groups()
remembered = (self.state.profile or {}).get("host_map", {})
devices = sorted(((self.engine.device_label(device_id), device_id) for device_id in self.engine.devices),
key=lambda item: item[0].casefold())
table = QTableWidget(len(self.host_groups), 3)
table.setHorizontalHeaderLabels(["Hypervisor-Host", "VMs", "NetBox-Gerät"])
table.verticalHeader().setVisible(False)
table.verticalHeader().setDefaultSectionSize(46)
table.setShowGrid(False)
table.setAlternatingRowColors(True)
table.setSelectionMode(QTableWidget.NoSelection)
table.setFocusPolicy(Qt.NoFocus)
table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
table.horizontalHeader().setSectionResizeMode(2, QHeaderView.Stretch)
table.setColumnWidth(1, 60)
table.setFixedHeight(46 * min(len(self.host_groups), 4) + 40)
for row, group in enumerate(self.host_groups):
item = QTableWidgetItem(f"{group['host']} · {group['source']}")
item.setToolTip("\n".join(sorted(vm["name"] for vm in group["vms"])))
table.setItem(row, 0, item)
count = QTableWidgetItem(str(len(group["vms"])))
count.setTextAlignment(Qt.AlignCenter)
table.setItem(row, 1, count)
combo = SearchableComboBox("NetBox-Gerät suchen …")
current = remembered.get(group["key"])
if current not in self.engine.devices and current != NO_DEVICE:
current = None
combo.set_items([("– nicht zuordnen –", NO_DEVICE), *devices], current)
holder = QWidget()
holder_layout = QHBoxLayout(holder)
holder_layout.setContentsMargins(0, 4, 8, 4)
holder_layout.addWidget(combo)
table.setCellWidget(row, 2, holder)
group["combo"] = combo
return table
def _build_target_page(self): def _build_target_page(self):
page = QWidget() page = QWidget()
layout = QVBoxLayout(page) layout = QVBoxLayout(page)
@@ -187,6 +235,11 @@ class ImportWizard(QDialog):
group["status"] = status group["status"] = status
combo.activated.connect(lambda _index, g=group: (g.update(how="manual"), self._clusters_changed())) combo.activated.connect(lambda _index, g=group: (g.update(how="manual"), self._clusters_changed()))
layout.addWidget(self.cluster_table) layout.addWidget(self.cluster_table)
host_table = self._build_host_table()
if self.host_groups:
layout.addWidget(label("Auf welches NetBox-Gerät soll jeder Hypervisor-Host gemappt werden?",
muted=True, wrap=True))
layout.addWidget(host_table)
form = QFormLayout() form = QFormLayout()
form.setHorizontalSpacing(18) form.setHorizontalSpacing(18)
@@ -290,6 +343,10 @@ class ImportWizard(QDialog):
if self._selected_cluster(group) is None] if self._selected_cluster(group) is None]
if missing: if missing:
return None, "Bitte für folgende Hypervisor-Cluster einen NetBox-Cluster wählen: " + ", ".join(missing) return None, "Bitte für folgende Hypervisor-Cluster einen NetBox-Cluster wählen: " + ", ".join(missing)
unmapped = [group["host"] for group in self.host_groups if group["combo"].valid_data() is None]
if unmapped:
return None, ("Bitte für folgende Hypervisor-Hosts ein NetBox-Gerät wählen "
"(oder „nicht zuordnen“): " + ", ".join(unmapped))
tenant = self.tenant.valid_data() tenant = self.tenant.valid_data()
vrf = self.vrf.currentData() vrf = self.vrf.currentData()
if not tenant: if not tenant:
@@ -307,8 +364,10 @@ class ImportWizard(QDialog):
"label": group["cluster"] or "(ohne Cluster)", "label": group["cluster"] or "(ohne Cluster)",
"count": len(group["vms"]), "count": len(group["vms"]),
} }
hosts = {group["key"]: group["combo"].valid_data() for group in self.host_groups}
return { return {
"clusters": clusters, "clusters": clusters,
"hosts": hosts,
"tenant": tenant, "tenant": tenant,
"tenant_id": self.engine.tenants[tenant], "tenant_id": self.engine.tenants[tenant],
"vrf_mode": "new" if vrf == NEW_VRF else ("global" if vrf == GLOBAL_VRF else "existing"), "vrf_mode": "new" if vrf == NEW_VRF else ("global" if vrf == GLOBAL_VRF else "existing"),
@@ -508,6 +567,10 @@ class ImportWizard(QDialog):
] ]
rows = [ rows = [
("Cluster", "\n".join(cluster_lines)), ("Cluster", "\n".join(cluster_lines)),
*([("Hosts", "\n".join(
f"{group['host']} → " + ("nicht zuordnen" if target["hosts"][group["key"]] == NO_DEVICE
else self.engine.device_label(target["hosts"][group["key"]]))
for group in self.host_groups))] if self.host_groups else []),
("Mandant", target["tenant"]), ("Mandant", target["tenant"]),
("Standard-VRF", vrf_text), ("Standard-VRF", vrf_text),
("Virtuelle Maschinen", f"{len(self.vms)} gesamt · {new} werden angelegt · {existing} aktualisiert"), ("Virtuelle Maschinen", f"{len(self.vms)} gesamt · {new} werden angelegt · {existing} aktualisiert"),
@@ -581,6 +644,7 @@ class ImportWizard(QDialog):
if self.state.profile is not None: if self.state.profile is not None:
remembered = self.state.profile.setdefault("cluster_map", {}) remembered = self.state.profile.setdefault("cluster_map", {})
remembered.update({key: item["name"] for key, item in target["clusters"].items()}) remembered.update({key: item["name"] for key, item in target["clusters"].items()})
self.state.profile.setdefault("host_map", {}).update(target["hosts"])
self.state.touch() self.state.touch()
log_bus.entry.connect(self._append_log) log_bus.entry.connect(self._append_log)
self.run_progress.setRange(0, len(vms)) self.run_progress.setRange(0, len(vms))
@@ -607,7 +671,9 @@ class ImportWizard(QDialog):
break break
ctx.progress(index, len(vms), vm["name"]) ctx.progress(index, len(vms), vm["name"])
try: try:
outcome = engine.sync_vm(vm, cluster_ids[cluster_key(vm)], target["tenant_id"], vrf_id) device_id = target["hosts"].get(host_key(vm))
outcome = engine.sync_vm(vm, cluster_ids[cluster_key(vm)], target["tenant_id"], vrf_id,
None if device_id == NO_DEVICE else device_id)
results[outcome] += 1 results[outcome] += 1
except Exception as error: # noqa: BLE001 except Exception as error: # noqa: BLE001
results["failed"].append(f"{vm['name']}: {error}") results["failed"].append(f"{vm['name']}: {error}")