netbox-docker/startup_scripts/270_primary_ips.py

45 lines
1.4 KiB
Python
Raw Normal View History

2020-06-04 13:46:40 -05:00
from dcim.models import Device
from ipam.models import IPAddress
from virtualization.models import VirtualMachine
from startup_script_utils import load_yaml
import sys
def link_primary_ip(assets, asset_model):
for params in assets:
primary_ip_fields = set(params) & {'primary_ip4', 'primary_ip6'}
if not primary_ip_fields:
continue
for assoc, details in optional_assocs.items():
if assoc in params:
model, field = details
query = { field: params.pop(assoc) }
try:
params[assoc] = model.objects.get(**query)
except model.DoesNotExist:
primary_ip_fields -= {assoc}
2020-10-18 04:31:48 -05:00
print(f"⚠️ IP Address '{query[field]}' not found")
2020-06-04 13:46:40 -05:00
asset = asset_model.objects.get(name=params['name'])
for field in primary_ip_fields:
if getattr(asset, field) != params[field]:
setattr(asset, field, params[field])
2020-10-18 04:31:48 -05:00
print(f"🔗 Define primary IP '{params[field].address}' on '{asset.name}'")
2020-06-04 13:46:40 -05:00
asset.save()
devices = load_yaml('/opt/netbox/initializers/devices.yml')
virtual_machines = load_yaml('/opt/netbox/initializers/virtual_machines.yml')
optional_assocs = {
'primary_ip4': (IPAddress, 'address'),
'primary_ip6': (IPAddress, 'address')
}
if devices is None and virtual_machines is None:
sys.exit()
elif devices is not None:
link_primary_ip(devices, Device)
elif virtual_machines is not None:
link_primary_ip(virtual_machines, VirtualMachine)