Skip to content

Commit 5ff0285

Browse files
authored
add parent/child support for loading device roles (#127)
* NetBox has supported a parent/child structure for device roles since 4.3. This adds parent support to loading of device roles. * update device_roles.yml with example for parent/child support (#127)
1 parent 154d977 commit 5ff0285

2 files changed

Lines changed: 29 additions & 3 deletions

File tree

src/netbox_initializers/initializers/device_roles.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from dcim.models import DeviceRole
22
from netbox.choices import ColorChoices
3+
from django.core.exceptions import ObjectDoesNotExist
34

45
from netbox_initializers.initializers.base import BaseInitializer, register_initializer
56

@@ -11,9 +12,26 @@ def load_data(self):
1112
device_roles = self.load_yaml()
1213
if device_roles is None:
1314
return
15+
1416
for params in device_roles:
1517
tags = params.pop("tags", None)
1618

19+
# Resolve parent role (accept slug or name; try slug first, then name)
20+
if "parent" in params and params["parent"] is not None:
21+
parent_value = params.pop("parent")
22+
23+
parent_obj = None
24+
try:
25+
parent_obj = DeviceRole.objects.get(slug=parent_value)
26+
except ObjectDoesNotExist:
27+
try:
28+
parent_obj = DeviceRole.objects.get(name=parent_value)
29+
except ObjectDoesNotExist:
30+
raise ValueError(f"DeviceRole parent '{parent_value}' not found by slug or name")
31+
32+
if parent_obj:
33+
params["parent"] = parent_obj
34+
1735
if "color" in params:
1836
color = params.pop("color")
1937

@@ -22,9 +40,7 @@ def load_data(self):
2240
params["color"] = color_tpl[0]
2341

2442
matching_params, defaults = self.split_params(params)
25-
device_role, created = DeviceRole.objects.get_or_create(
26-
**matching_params, defaults=defaults
27-
)
43+
device_role, created = DeviceRole.objects.get_or_create(**matching_params, defaults=defaults)
2844

2945
if created:
3046
print("🎨 Created device role", device_role.name)

src/netbox_initializers/initializers/yaml/device_roles.yml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
1+
# - name: Network Structure
2+
# slug: network-structure
3+
# description: Network infrastructure device providing connectivity between systems
4+
# - name: Gateway
5+
# slug: gateway
6+
# parent: network-structure
7+
# description: Network edge device category (routing, firewalling, protocol coupling)
8+
# color: White
19
# - name: switch
210
# slug: switch
11+
# parent: network-structure
312
# color: Grey
413
# - name: router
514
# slug: router
15+
# parent: gateway
616
# color: Cyan
717
# - name: load-balancer
818
# slug: load-balancer

0 commit comments

Comments
 (0)