feat: export device types as YAML in devicetype-library format

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-26 09:21:58 +01:00
1 parent 713556a33e
commit 280c0e0315
8 files changed
+242 -3

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
from netbox.plugins import PluginConfig, get_plugin_config
__version__ = "0.29.2"
__version__ = "0.30.0"
class NetBoxUtilitiesConfig(PluginConfig):
+142
View File
@@ -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: <Manufacturer>/<slug>.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()
+46
View File
@@ -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
+24
View File
@@ -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,
]
@@ -0,0 +1,4 @@
<a href="{{ url }}" class="btn btn-outline-secondary">
<i class="mdi mdi-file-code-outline" aria-hidden="true"></i>
{{ label }}
</a>
+11 -1
View File
@@ -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/<int:pk>/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