From 280c0e031510b044d605a91a8831eddecd481472 Mon Sep 17 00:00:00 2001 From: Louis Date: Thu, 26 Nov 2026 09:21:58 +0100 Subject: [PATCH] feat: export device types as YAML in devicetype-library format Co-Authored-By: Claude Opus 5.5 --- README.md | 13 ++ netbox_utilities/__init__.py | 2 +- netbox_utilities/devicetype_export.py | 142 ++++++++++++++++++ netbox_utilities/devicetype_views.py | 46 ++++++ netbox_utilities/template_content.py | 24 +++ .../devicetype_yaml_button.html | 4 + netbox_utilities/urls.py | 12 +- pyproject.toml | 2 +- 8 files changed, 242 insertions(+), 3 deletions(-) create mode 100644 netbox_utilities/devicetype_export.py create mode 100644 netbox_utilities/devicetype_views.py create mode 100644 netbox_utilities/templates/netbox_utilities/devicetype_yaml_button.html diff --git a/README.md b/README.md index ffe7bd0..d574812 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ Plugin settings: - The rack view of the optional [MrBlake NetBox Topology Views](https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views) plugin renders partial-width devices correctly. - Upload multiple images at once in an object's **Images** tab. - Install multiple modules of the same type into free module bays in one step. +- Export device types as YAML in the devicetype-library format (single type or the filtered list as ZIP). - Optional bulk save for devices moved in NetBox Reorder Rack. - Rack widths are preserved by the optional [NetBox-Export](https://git.mrblake.cc/MrBlake/NetBox-Export) export/import. - Cables and wireless links can be assigned to one or more VLANs. @@ -763,6 +764,18 @@ error occurs, the whole rack stays unchanged. Every moved device still gets a normal changelog entry. Versions other than `1.1.4` are left untouched and only produce a log message. +### Exporting device types as YAML + +Device type detail pages get an **Export YAML** button that downloads the type +in the [devicetype-library](https://github.com/netbox-community/devicetype-library) +format (manufacturer, model, slug, dimensions, airflow, weight and all component +templates: console/power ports, outlets, interfaces, front/rear ports incl. their +mapping, module/device bays and inventory items). Fields at their default value are +omitted. The file can be imported again via *Device Types → Import*. + +The device type list gets the same button: it exports every type matching the +current filters as `device-types.zip`, laid out as `/.yaml`. + ### Uploading multiple images In the **Images** tab of supported objects, the single upload is replaced by diff --git a/netbox_utilities/__init__.py b/netbox_utilities/__init__.py index e344170..80f2d6e 100644 --- a/netbox_utilities/__init__.py +++ b/netbox_utilities/__init__.py @@ -1,6 +1,6 @@ from netbox.plugins import PluginConfig, get_plugin_config -__version__ = "0.29.2" +__version__ = "0.30.0" class NetBoxUtilitiesConfig(PluginConfig): diff --git a/netbox_utilities/devicetype_export.py b/netbox_utilities/devicetype_export.py new file mode 100644 index 0000000..5217f82 --- /dev/null +++ b/netbox_utilities/devicetype_export.py @@ -0,0 +1,142 @@ +"""Export device types as YAML in the community devicetype-library format. + +The output can be re-imported through NetBox's own "Device Types > Import" +form or contributed to https://github.com/netbox-community/devicetype-library. +""" + +import io +import zipfile + +import yaml +from django.apps import apps +from django.utils.text import slugify + +# (YAML key, related manager on DeviceType, fields exported per component) +COMPONENTS = [ + ("console-ports", "consoleporttemplates", ["type"]), + ("console-server-ports", "consoleserverporttemplates", ["type"]), + ("power-ports", "powerporttemplates", ["type", "maximum_draw", "allocated_draw"]), + ("power-outlets", "poweroutlettemplates", ["type", "power_port", "feed_leg"]), + ("interfaces", "interfacetemplates", ["type", "mgmt_only", "poe_mode", "poe_type"]), + ("rear-ports", "rearporttemplates", ["type", "color", "positions"]), + ("front-ports", "frontporttemplates", ["type", "color", "positions"]), + ("module-bays", "modulebaytemplates", ["position"]), + ("device-bays", "devicebaytemplates", []), + ("inventory-items", "inventoryitemtemplates", ["manufacturer", "part_id"]), +] + +DEVICE_TYPE_FIELDS = [ + "part_number", + "u_height", + "exclude_from_utilization", + "is_full_depth", + "subdevice_role", + "airflow", + "weight", + "weight_unit", + "description", + "comments", +] + +# Values that equal NetBox's defaults are dropped to keep the files short. +DEFAULTS = { + "exclude_from_utilization": False, + "mgmt_only": False, + "positions": 1, + "color": "", +} + + +def _plain(value): + if value is None or value == "": + return None + if hasattr(value, "is_finite"): # Decimal + return int(value) if value == value.to_integral_value() else float(value) + if hasattr(value, "_meta"): # FK (power_port, manufacturer) + return getattr(value, "name", str(value)) + return value + + +def _put(target, key, value): + value = _plain(value) + if value is None or DEFAULTS.get(key, object()) == value: + return + target[key] = value + + +def _front_port_mappings(device_type): + """{front_port_id: (rear_port_name, rear_port_position)} for single mappings (NetBox >= 4.5).""" + try: + model = apps.get_model("dcim", "PortTemplateMapping") + except LookupError: + return {} + mappings = {} + for mapping in model.objects.filter(device_type=device_type).select_related("rear_port"): + mappings.setdefault(mapping.front_port_id, []).append(mapping) + return { + front_id: (items[0].rear_port.name, items[0].rear_port_position) + for front_id, items in mappings.items() + if len(items) == 1 + } + + +def device_type_to_dict(device_type): + data = { + "manufacturer": device_type.manufacturer.name, + "model": device_type.model, + "slug": device_type.slug, + } + for field in DEVICE_TYPE_FIELDS: + _put(data, field, getattr(device_type, field, None)) + + mappings = None + for key, manager, fields in COMPONENTS: + items = [] + for component in getattr(device_type, manager).all(): + item = {"name": component.name} + label = getattr(component, "label", "") + if label: + item["label"] = label + for field in fields: + if hasattr(component, field): + _put(item, field, getattr(component, field)) + if key == "front-ports": + if mappings is None: + mappings = _front_port_mappings(device_type) + legacy_rear = getattr(component, "rear_port", None) + if component.pk in mappings: + item["rear_port"], item["rear_port_position"] = mappings[component.pk] + elif legacy_rear is not None: # NetBox < 4.5 + item["rear_port"] = legacy_rear.name + item["rear_port_position"] = component.rear_port_position + if component.description: + item["description"] = component.description + items.append(item) + if items: + data[key] = items + return data + + +def device_type_to_yaml(device_type): + return yaml.safe_dump( + device_type_to_dict(device_type), + sort_keys=False, + allow_unicode=True, + default_flow_style=False, + ) + + +def filename(device_type): + return f"{device_type.slug or slugify(device_type.model)}.yaml" + + +def device_types_to_zip(device_types): + """ZIP laid out like the devicetype-library: /.yaml""" + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive: + for device_type in device_types: + archive.writestr( + f"{device_type.manufacturer.name}/{filename(device_type)}", + device_type_to_yaml(device_type), + ) + return buffer.getvalue() diff --git a/netbox_utilities/devicetype_views.py b/netbox_utilities/devicetype_views.py new file mode 100644 index 0000000..1f6ab0d --- /dev/null +++ b/netbox_utilities/devicetype_views.py @@ -0,0 +1,46 @@ +from dcim.filtersets import DeviceTypeFilterSet +from dcim.models import DeviceType +from django.contrib.auth.mixins import LoginRequiredMixin +from django.core.exceptions import PermissionDenied +from django.http import HttpResponse +from django.shortcuts import get_object_or_404 +from django.views import View + +from . import devicetype_export + +PREFETCH = [ + "consoleporttemplates", + "consoleserverporttemplates", + "powerporttemplates", + "poweroutlettemplates__power_port", + "interfacetemplates", + "rearporttemplates", + "frontporttemplates", + "modulebaytemplates", + "devicebaytemplates", + "inventoryitemtemplates__manufacturer", +] + + +def _queryset(request): + if not request.user.has_perm("dcim.view_devicetype"): + raise PermissionDenied + return DeviceType.objects.restrict(request.user, "view").select_related("manufacturer").prefetch_related(*PREFETCH) + + +class DeviceTypeYAMLExportView(LoginRequiredMixin, View): + def get(self, request, pk): + device_type = get_object_or_404(_queryset(request), pk=pk) + response = HttpResponse(devicetype_export.device_type_to_yaml(device_type), content_type="application/yaml; charset=utf-8") + response["Content-Disposition"] = f'attachment; filename="{devicetype_export.filename(device_type)}"' + return response + + +class DeviceTypeBulkYAMLExportView(LoginRequiredMixin, View): + """Exports the current (filtered) device type list, or ?id=... selections, as a ZIP.""" + + def get(self, request): + device_types = DeviceTypeFilterSet(request.GET, queryset=_queryset(request)).qs.order_by("manufacturer__name", "model") + response = HttpResponse(devicetype_export.device_types_to_zip(device_types), content_type="application/zip") + response["Content-Disposition"] = 'attachment; filename="device-types.zip"' + return response diff --git a/netbox_utilities/template_content.py b/netbox_utilities/template_content.py index 70fe6f6..afda31a 100644 --- a/netbox_utilities/template_content.py +++ b/netbox_utilities/template_content.py @@ -213,6 +213,29 @@ class ConnectionVLANContent(PluginTemplateExtension): ) +class DeviceTypeExportContent(PluginTemplateExtension): + models = ["dcim.devicetype"] + + def _label(self, bulk=False): + german = (translation.get_language() or "").startswith("de") + return "YAML exportieren" if german else "Export YAML" + + def buttons(self): + device_type = self.context["object"] + url = reverse("plugins:netbox_utilities:devicetype_yaml", kwargs={"pk": device_type.pk}) + return self.render("netbox_utilities/devicetype_yaml_button.html", {"url": url, "label": self._label()}) + + def list_buttons(self): + request = self.context["request"] + url = reverse("plugins:netbox_utilities:devicetype_bulk_yaml") + query = request.GET.copy() + for key in ("page", "per_page", "sort", "export"): + query.pop(key, None) + if query: + url = f"{url}?{query.urlencode()}" + return self.render("netbox_utilities/devicetype_yaml_button.html", {"url": url, "label": self._label(True)}) + + class RackUtilitiesContent(PluginTemplateExtension): models = ["dcim.rack"] @@ -235,6 +258,7 @@ template_extensions = [ DeviceUtilitiesContent, ConnectionVLANContent, RackUtilitiesContent, + DeviceTypeExportContent, ClusterHardwareContent, VirtualMachineHardwareContent, ] diff --git a/netbox_utilities/templates/netbox_utilities/devicetype_yaml_button.html b/netbox_utilities/templates/netbox_utilities/devicetype_yaml_button.html new file mode 100644 index 0000000..bb2365f --- /dev/null +++ b/netbox_utilities/templates/netbox_utilities/devicetype_yaml_button.html @@ -0,0 +1,4 @@ + + + {{ label }} + diff --git a/netbox_utilities/urls.py b/netbox_utilities/urls.py index e482fa6..e48b241 100644 --- a/netbox_utilities/urls.py +++ b/netbox_utilities/urls.py @@ -3,7 +3,7 @@ from django.urls import include, path from netbox.plugins import get_plugin_config from utilities.urls import get_model_urls -from . import disk_views, hardware_views, switch_port_views, views # noqa: F401 - hardware_views registers its model views +from . import devicetype_views, disk_views, hardware_views, switch_port_views, views # noqa: F401 - hardware_views registers its model views app_name = "netbox_utilities" @@ -17,6 +17,16 @@ urlpatterns = [ views.RackElevationOfflineSVGView.as_view(), name="rack_elevation_offline_svg", ), + path( + "device-types/export-yaml/", + devicetype_views.DeviceTypeBulkYAMLExportView.as_view(), + name="devicetype_bulk_yaml", + ), + path( + "device-types//export.yaml", + devicetype_views.DeviceTypeYAMLExportView.as_view(), + name="devicetype_yaml", + ), path("settings/", views.UtilitiesSettingsView.as_view(), name="settings"), path("tenant/select/", views.SelectTenantView.as_view(), name="select_tenant"), # Datenträger diff --git a/pyproject.toml b/pyproject.toml index 7b51acf..d9ffa72 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "netbox-utilities" -version = "0.29.2" +version = "0.30.0" description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export and bulk operations for NetBox 4.6/4.7" readme = "README.md" requires-python = ">=3.12"