VLAN Groups can be scoped to multiple types

This commit is contained in:
Tobias Genannt 2021-04-07 15:18:33 +02:00
parent 1c4b6741ac
commit 9874cef369
2 changed files with 33 additions and 7 deletions

View File

@ -1,6 +1,24 @@
# - name: VLAN group 1
# site: AMS 1
# scope_type: "dcim.region"
# scope: Amsterdam
# slug: vlan-group-1
# - name: VLAN group 2
# site: AMS 1
# scope_type: "dcim.site"
# scope: AMS 1
# slug: vlan-group-2
# - name: VLAN group 3
# scope_type: "dcim.location"
# scope: cage 101
# slug: vlan-group-3
# - name: VLAN group 4
# scope_type: "dcim.rack"
# scope: rack-01
# slug: vlan-group-4
# - name: VLAN group 5
# scope_type: "virtualization.cluster"
# scope: cluster1
# slug: vlan-group-5
# - name: VLAN group 6
# scope_type: "virtualization.clustergroup"
# scope: Group 1
# slug: vlan-group-6

View File

@ -1,6 +1,6 @@
import sys
from dcim.models import Site
from django.contrib.contenttypes.models import ContentType
from ipam.models import VLANGroup
from startup_script_utils import load_yaml, pop_custom_fields, set_custom_fields_values
@ -9,7 +9,7 @@ vlan_groups = load_yaml("/opt/netbox/initializers/vlan_groups.yml")
if vlan_groups is None:
sys.exit()
optional_assocs = {"site": (Site, "name")}
optional_assocs = {"scope": (None, "name")}
for params in vlan_groups:
custom_field_data = pop_custom_fields(params)
@ -18,9 +18,17 @@ for params in vlan_groups:
if assoc in params:
model, field = details
query = {field: params.pop(assoc)}
params[assoc] = model.objects.get(**query)
# Get model from Contenttype
scope_type = params.pop("scope_type", None)
if not scope_type:
print("scope_type is missing from VLAN Group")
continue
app_label, model = str(scope_type).split(".")
ct = ContentType.objects.get(app_label=app_label, model=model)
if not ct:
print(f"ContentType for app_label = '{app_label}' and model = '{model}' not found")
continue
params["scope_id"] = ct.model_class().objects.get(**query).id
vlan_group, created = VLANGroup.objects.get_or_create(**params)
if created: