From 9a1e7020996116f678358c54fd0cf7a60562a0ad Mon Sep 17 00:00:00 2001 From: MrBlake Date: Wed, 30 Sep 2026 13:36:42 +0200 Subject: [PATCH 1/3] docs: rewrite README in English with standard structure Co-Authored-By: Claude Opus 5.5 --- README.md | 273 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 161 insertions(+), 112 deletions(-) diff --git a/README.md b/README.md index a93ff07..1c2b7db 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,68 @@ # NetBox-Export -NetBox-Export ist ein Plugin für NetBox 4.6.x und 4.7.x. Es exportiert einen abgegrenzten -Mandanten- oder Standortbereich als portables ZIP-Archiv und importiert ihn in -eine zweite NetBox-Instanz. +Export a scoped tenant or site area as a portable ZIP archive and import it into +a second NetBox instance. -Unterstützte Startpunkte: +| | | +|---|---| +| **Plugin name** | `netbox_export` | +| **Package** | `netbox-export` | +| **NetBox** | `4.6.0` – `4.7.x` | +| **Python** | `>=3.12` | +| **Repository** | | -- Mandantengruppe einschließlich Untergruppen und Mandanten -- einzelner Mandant -- Region einschließlich Unterregionen und Standorten -- einzelner Standort -- Lokation einschließlich Unterlokationen +## Features -Der Export folgt den Besitzbeziehungen zu DCIM-, IPAM-, Circuit-, -Virtualisierungs-, VPN-, Wireless-, Kontakt-, Tag- und Bilddaten. Benötigte -Stammdaten werden als Abhängigkeiten mitgenommen. Primärschlüssel der -Quellinstanz werden nie direkt als Zielschlüssel verwendet. +Supported starting points: + +- tenant group including sub-groups and tenants +- single tenant +- region including sub-regions and sites +- single site +- location including sub-locations + +The export follows ownership relations to DCIM, IPAM, circuit, virtualisation, +VPN, wireless, contact, tag and image data. Required master data is included as +dependencies. Primary keys of the source instance are never used directly as +target keys. + +## Compatibility + +- NetBox `4.6.0` – `4.7.x` +- Python `>=3.12` +- Source and target must run the same NetBox version and the same plugins, + plugin versions and migrations. ## Installation -Das Plugin muss auf beiden NetBox-Instanzen installiert sein. +The plugin must be installed on **both** NetBox instances. All paths assume a +standard installation under `/opt/netbox`. + +### 1. Install the package ```bash -cd /opt/netbox -source venv/bin/activate -pip install --upgrade --force-reinstall \ +/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \ "git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main" - -# Prüfen, ob das Modul im NetBox-venv verfügbar ist -python -c "import netbox_export; print(netbox_export.__file__)" ``` -In `configuration.py` ergänzen: +For reproducible production installs, replace `main` with a release tag or a +full commit ID. + +### 2. Add the plugin to `local_requirements.txt` + +This makes `upgrade.sh` reinstall the plugin automatically on every NetBox upgrade: + +```bash +grep -qxF "git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main" /opt/netbox/local_requirements.txt \ + || echo "git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main" | sudo tee -a /opt/netbox/local_requirements.txt +``` + +If the repository is private, the NetBox server needs a read-only deploy token +or an SSH key. Do not store credentials in `local_requirements.txt`. + +### 3. Enable the plugin + +In `/opt/netbox/netbox/netbox/configuration.py`: ```python PLUGINS = [ @@ -43,122 +74,140 @@ PLUGINS_CONFIG = { "max_objects": 50000, "max_archive_size_mb": 250, "query_batch_size": 500, - # Auf beiden Instanzen identisch setzen, um Archive zu signieren. - "archive_signing_key": "eine-lange-zufaellige-geheime-zeichenfolge", + # Set identically on both instances to sign archives. + "archive_signing_key": "a-long-random-secret-string", }, } ``` -Anschließend: +If other plugins are already configured, add `netbox_export` to the existing +list and dictionary instead of replacing them. + +### 4. Apply migrations, collect static files, restart ```bash cd /opt/netbox/netbox -python manage.py migrate netbox_export -python manage.py collectstatic --no-input +/opt/netbox/venv/bin/python manage.py migrate netbox_export +/opt/netbox/venv/bin/python manage.py collectstatic --no-input sudo systemctl restart netbox netbox-rq ``` -Falls `ModuleNotFoundError: No module named 'netbox_export'` erscheint, wurde -das Paket nicht in `/opt/netbox/venv` installiert. In diesem Fall den obigen -Installationsblock erneut ausführen und darauf achten, dass -`/opt/netbox/venv/bin/python` verwendet wird: +If `ModuleNotFoundError: No module named 'netbox_export'` appears, the package +was not installed into `/opt/netbox/venv`. Check with: ```bash -/opt/netbox/venv/bin/python -m pip install --upgrade --force-reinstall \ - "git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main" -/opt/netbox/venv/bin/python -c \ - "import netbox_export; print(netbox_export.__file__)" +/opt/netbox/venv/bin/python -c "import netbox_export; print(netbox_export.__file__)" ``` -Bei einer Docker-Installation wird das Paket in das eigene NetBox-Image -aufgenommen; danach wird der Container mit dem aktivierten Plugin neu gebaut und -die Migration ausgeführt. +For Docker installations, add the package to your NetBox image, rebuild the +container with the plugin enabled and run the migration. -## Verwendung +## Update -Die Oberfläche liegt unter **Plugins > NetBox-Export > Export / Import** und ist -aus Sicherheitsgründen nur für Superuser sichtbar. +```bash +/opt/netbox/venv/bin/pip install --upgrade --force-reinstall \ + "git+https://git.mrblake.cc/MrBlake/NetBox-Export.git@main" -1. Auf Instanz A den Typ und das konkrete Objekt wählen und das ZIP exportieren. -2. Auf Instanz B das ZIP zunächst mit **Nur prüfen** verarbeiten. -3. Nach erfolgreichem Prüflauf **Nur prüfen** deaktivieren, den schreibenden - Import bestätigen und das Archiv erneut hochladen. +cd /opt/netbox/netbox +/opt/netbox/venv/bin/python manage.py migrate netbox_export +/opt/netbox/venv/bin/python manage.py collectstatic --no-input +sudo systemctl restart netbox netbox-rq +``` -Der Import läuft atomar. Bei einem Fehler werden alle Datenbankänderungen -zurückgerollt. Die Konfliktstrategie **Aktualisieren** nutzt zuerst die dauerhaft -gespeicherte Zuordnung aus Quellinstanz, Modell und Quell-ID; bei einem ersten -Import werden vorhandene Objekte über ihre eindeutigen Fachschlüssel erkannt. +`--force-reinstall` makes pip pick up branch changes even if the package +version has not been bumped. Update source and target instance together. -## Verhalten und Grenzen +When NetBox itself is upgraded, `upgrade.sh` reinstalls the plugin from +`local_requirements.txt` and runs migrations and `collectstatic`: -- Quelle und Ziel müssen dieselbe unterstützte NetBox-Version (4.6.x oder 4.7.x) und dieselben Plugins/Modelle verwenden. -- Benutzerkonten und Berechtigungen werden nicht exportiert. Fehlende oder - nicht eindeutige Referenzen auf Benutzer und Gruppen werden ausgelassen und - nach dem Import als Warnung angezeigt. Benötigt ein neuer Datensatz zwingend - eine solche Referenz, wird nur dieser Datensatz übersprungen. -- Der Import erstellt und aktualisiert Objekte. Zielobjekte, die im Archiv nicht - vorkommen, werden bewusst nicht gelöscht. -- Fehlende Bilddateien werden im Archiv vermerkt, können aber nicht rekonstruiert - werden. -- Große Exporte werden synchron verarbeitet. `max_objects` begrenzt Laufzeit und - Speicherverbrauch. -- `query_batch_size` steuert die Größe gebündelter Datenbankabfragen. Der - Standardwert `500` ist für typische PostgreSQL-Installationen geeignet; - Werte zwischen `250` und `1000` erlauben eine Anpassung an Arbeitsspeicher und - Datenbankleistung. +```bash +sudo /opt/netbox/upgrade.sh +sudo systemctl restart netbox netbox-rq +``` -## Plugin-Kompatibilität +## Uninstall -Der Exportgraph berücksichtigt installierte, mandantenbezogene Modelle und -Dateien aus NetBox-SLM, Netbox-DokiWiki und NetBox-VM-Import. Private oder -temporäre Plugin-Modelle werden nicht exportiert. Die von Netbox-Utilities -erzwungene Mandantenpflicht wird beim Import berücksichtigt: Das Zielobjekt wird -erst gespeichert, nachdem sein Mandant importiert und zugeordnet wurde. Ist kein -Mandant auflösbar, wird automatisch ein vorhandener Mandant `Auto-Import` -verwendet oder neu angelegt. Der Importbericht weist darauf hin. -Beziehungen, die Teil einer Plugin-Datenbankprüfung sind, werden vollständig -aufgelöst, bevor das Objekt erstmals gespeichert wird. Dies betrifft unter -anderem die Plattformzuordnung von NetBox-SLM-Softwareinstallationen. -Eindeutige optionale Beziehungen wie die primären IP-Adressen von Geräten und -virtuellen Maschinen werden in einer zweiten Phase zugewiesen. Eine veraltete -Zielzuordnung wird dabei atomar gelöst und als Warnung protokolliert. -Gespeicherte Importzuordnungen werden bei Wiederholungsimporten gegen den -aktuellen Fachschlüssel geprüft. Existiert das Objekt bereits unter diesem -Schlüssel, wird die Zuordnung korrigiert, statt ein Duplikat anzulegen. -Bei neuen NetBox-Modulen wird die automatische Komponentenreplikation -deaktiviert. Ports, Interfaces und Bays werden stattdessen ausschließlich aus -den Archivdatensätzen angelegt beziehungsweise vorhandenen Komponenten -zugeordnet. -Geräte werden in einer separaten Abschlussphase im Rack platziert, damit auch -Positionswechsel ohne temporäre Doppelbelegung funktionieren. Bei fremden -Belegungen löst **Aktualisieren** das Zielgerät mit Warnung von seiner Position, -**Überspringen** lässt das importierte Gerät positionslos und **Import abbrechen** -meldet den Rackplatzkonflikt vor dem Datenbankfehler. Mehr-U- und -Full-Depth-Belegungen werden dabei berücksichtigt. -Front-/Rear-Port-Zuordnungen von Patchpanels werden als eigene Datensätze -exportiert und bei **Aktualisieren** auf den Stand der Quelle gebracht. Nach dem -Import stößt das Plugin für alle enthaltenen Kabel die NetBox-eigene -Neuberechnung der Kabelpfade an. Für diese Korrektur muss mit Plugin-Version -`0.3.12` oder neuer ein neues Archiv auf der Quellinstanz erzeugt werden, da -ältere Archive keine Portzuordnungen enthalten. -PostgreSQL-Range-Felder, darunter die erlaubten VLAN-ID-Bereiche einer -VLAN-Gruppe, werden typisiert im Archiv gespeichert. Der Import erkennt auch -die von älteren Plugin-Versionen als Text exportierten Range-Werte. -Bei Bildanhängen werden Breite und Höhe direkt aus der Bilddatei im Archiv -ermittelt. Dadurch sind die Pflichtfelder von NetBox auch im Prüflauf und bei -Dateispeichern ohne unmittelbaren Modell-Save gesetzt. Bilder oberhalb des von -NetBox verwendeten Limits von 25 Millionen Pixeln werden proportional auf -höchstens 20 Millionen Pixel verkleinert und im Importbericht als Warnung -ausgewiesen. Zum Schutz des Importprozesses bleibt eine harte Quellgrenze von -100 Millionen Pixeln bestehen. +1. Remove `"netbox_export"` from `PLUGINS` and `PLUGINS_CONFIG`. +2. Remove the line from `/opt/netbox/local_requirements.txt`. +3. Uninstall the package and restart NetBox: -Auf Quelle und Ziel müssen jeweils dieselben Plugin-Versionen und Migrationen -installiert sein. Verschlüsselte Zugangsdaten von NetBox-VM-Import sind nur bei -identischem Django-`SECRET_KEY` direkt nutzbar; andernfalls muss das Kennwort am -Ziel neu gesetzt werden. +```bash +/opt/netbox/venv/bin/pip uninstall netbox-export +sudo systemctl restart netbox netbox-rq +``` -## Tests +## Configuration + +| Key | Default | Description | +|---|---|---| +| `max_objects` | `50000` | Upper limit of objects per export (runtime and memory) | +| `max_archive_size_mb` | `250` | Maximum archive size | +| `query_batch_size` | `500` | Size of batched database queries; `250`–`1000` is reasonable | +| `archive_signing_key` | – | Shared secret to sign archives; must be identical on both instances | + +## Usage + +The UI is located under **Plugins > NetBox-Export > Export / Import** and, for +security reasons, is only visible to superusers. + +1. On instance A, choose the type and the specific object and export the ZIP. +2. On instance B, first process the ZIP with **Dry run only**. +3. After a successful dry run, disable **Dry run only**, confirm the writing + import and upload the archive again. + +The import is atomic: on error, all database changes are rolled back. The +conflict strategy **Update** first uses the stored mapping of source instance, +model and source ID; on a first import, existing objects are matched by their +unique natural keys. + +### Behaviour and limits + +- User accounts and permissions are not exported. Missing or ambiguous user and + group references are omitted and reported as warnings; if a new record + strictly requires such a reference, only that record is skipped. +- The import creates and updates objects. Target objects not contained in the + archive are intentionally **not** deleted. +- Missing image files are noted in the archive but cannot be reconstructed. +- Large exports are processed synchronously; `max_objects` limits runtime and memory. + +### Plugin compatibility + +- Tenant-related models and files of NetBox-SLM, Netbox-Documentation and + NetBox-VM-Import are included. Private or temporary plugin models are not exported. +- The mandatory tenant assignment of Netbox-Utilities is respected: an object is + only saved after its tenant has been imported. If no tenant can be resolved, + an existing tenant `Auto-Import` is used or created, and the import report + says so. +- Relations checked by plugin database constraints (e.g. the platform of + NetBox-SLM software installations) are resolved before the first save. +- Unique optional relations such as primary IPs of devices and VMs are assigned + in a second phase; stale target assignments are released atomically and logged. +- Stored import mappings are validated against the current natural key on + repeated imports, correcting the mapping instead of creating duplicates. +- Automatic component replication is disabled for new modules; ports, + interfaces and bays are created solely from archive records. +- Devices are placed in racks in a separate final phase so position swaps work + without temporary double occupancy. For foreign occupants, **Update** releases + the target device with a warning, **Skip** leaves the imported device without + a position, and **Abort import** reports the rack conflict. Multi-U and + full-depth occupancy are considered. +- Front/rear port mappings of patch panels are exported as separate records and + synced on **Update**; cable paths are recalculated after import. This requires + an archive created with version `0.3.12` or newer. +- PostgreSQL range fields (e.g. VLAN ID ranges of VLAN groups) are stored typed; + text values from older versions are still recognised. +- Image width and height are read from the archived file. Images above NetBox's + 25-megapixel limit are scaled down to at most 20 megapixels with a warning; a + hard source limit of 100 megapixels applies. +- Encrypted credentials of NetBox-VM-Import are only usable with an identical + Django `SECRET_KEY`; otherwise set the password again on the target. + +## Development and tests ```bash python -m pytest ``` + +## License + +Apache License 2.0 — see [LICENSE](LICENSE). From 0fdde044e1b6b62ee9c53f0162c42ef323bad2c9 Mon Sep 17 00:00:00 2001 From: MrBlake Date: Tue, 13 Oct 2026 14:14:49 +0200 Subject: [PATCH 2/3] Avoid deprecated select_related() call on Django 6.1 NetBox 4.7.2 ships Django 6.1, which deprecates select_related() without arguments (an error in Django 7). Only call it when the model has foreign keys; behaviour is unchanged. Verified with NetBox 4.7.2. Bump version to 0.3.14, the version Netbox-Utilities already expects for its rack width integration. Co-Authored-By: Claude Opus 5.5 --- netbox_export/services/exporter.py | 2 +- netbox_export/services/graph.py | 5 ++++- pyproject.toml | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/netbox_export/services/exporter.py b/netbox_export/services/exporter.py index b1d4f83..ef52ea0 100644 --- a/netbox_export/services/exporter.py +++ b/netbox_export/services/exporter.py @@ -39,7 +39,7 @@ def export_scope( "created_at": datetime.now(UTC).isoformat(), "source_instance": str(InstanceIdentity.local_id()), "source_netbox_version": getattr(getattr(settings, "RELEASE", None), "version", "4.6"), - "plugin_version": "0.3.13", + "plugin_version": "0.3.14", "scope": { "type": scope_type, "source_pk": str(scope_id), diff --git a/netbox_export/services/graph.py b/netbox_export/services/graph.py index 5c1cabf..8c4ce08 100644 --- a/netbox_export/services/graph.py +++ b/netbox_export/services/graph.py @@ -228,7 +228,10 @@ class ObjectGraph: ) for object_batch in _chunks(objects, self.query_batch_size): object_ids = [obj.pk for obj in object_batch] - queryset = model._default_manager.filter(pk__in=object_ids).select_related(*foreign_keys).order_by("pk") + queryset = model._default_manager.filter(pk__in=object_ids).order_by("pk") + if foreign_keys: + # select_related() without arguments is deprecated since Django 6.1. + queryset = queryset.select_related(*foreign_keys) if prefetch_fields: queryset = queryset.prefetch_related(*prefetch_fields) yield from queryset.iterator(chunk_size=self.query_batch_size) diff --git a/pyproject.toml b/pyproject.toml index 55702a8..4984f57 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "netbox-export" -version = "0.3.13" +version = "0.3.14" description = "Portable ZIP export and import for scoped NetBox data" readme = "README.md" requires-python = ">=3.12" From 44149acf1651b43619f294cb2387a64bb51fa914 Mon Sep 17 00:00:00 2001 From: MrBlake Date: Tue, 13 Oct 2026 15:21:11 +0200 Subject: [PATCH 3/3] Fix importing IP ranges IPRange.save() computes its size from start_address.ip, but the importer assigned the archived addresses as plain strings, so every archive containing IP ranges failed with "'str' object has no attribute 'ip'". Convert values of NetBox IP fields with the field's to_python(). This also affects NetBox 4.6. IP ranges also had no natural key, so importing into an instance that already contained the range created a duplicate. Match them by (vrf, start_address, end_address). Verified with a real export and repeated imports on NetBox 4.7.2; the version stays 0.3.14 because Netbox-Utilities only enables its integration for known versions. Co-Authored-By: Claude Opus 5.5 --- netbox_export/services/importer.py | 8 ++++++++ tests/test_range_import.py | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/netbox_export/services/importer.py b/netbox_export/services/importer.py index c3c0671..cc9e433 100644 --- a/netbox_export/services/importer.py +++ b/netbox_export/services/importer.py @@ -54,6 +54,7 @@ EXPLICIT_IDENTITIES = { "dcim.inventoryitem": ("device", "parent", "name"), "ipam.prefix": ("vrf", "prefix"), "ipam.ipaddress": ("vrf", "address"), + "ipam.iprange": ("vrf", "start_address", "end_address"), "ipam.vlan": ("group", "vid"), "circuits.circuit": ("provider", "cid"), "virtualization.virtualmachine": ("cluster", "tenant", "name"), @@ -169,9 +170,16 @@ def _coerce_model_field_value(field, value): and hasattr(base_field, "base_field") ): return [_coerce_range_value(base_field, item) for item in value] + if isinstance(value, str) and _is_netbox_ip_field(field): + # IPRange.save() computes its size from start_address.ip, so plain strings are not enough. + return field.to_python(value) return value +def _is_netbox_ip_field(field): + return any(cls.__name__ == "BaseIPField" for cls in type(field).__mro__) + + def _identity_candidates(model): explicit = EXPLICIT_IDENTITIES.get(model._meta.label_lower) if explicit: diff --git a/tests/test_range_import.py b/tests/test_range_import.py index 714dc70..890f0b0 100644 --- a/tests/test_range_import.py +++ b/tests/test_range_import.py @@ -54,3 +54,27 @@ def test_range_like_strings_remain_unchanged_for_normal_fields(): field = object() assert _coerce_model_field_value(field, "[1, 56)") == "[1, 56)" + + +class BaseIPField: + @staticmethod + def to_python(value): + return ("parsed", value) + + +class IPAddressField(BaseIPField): + pass + + +class CharField: + @staticmethod + def to_python(value): + raise AssertionError("plain fields must not be converted") + + +def test_netbox_ip_field_values_are_converted_for_model_save(): + assert _coerce_model_field_value(IPAddressField(), "192.0.2.1/24") == ("parsed", "192.0.2.1/24") + + +def test_other_string_values_are_left_unchanged(): + assert _coerce_model_field_value(CharField(), "192.0.2.1/24") == "192.0.2.1/24"