2021-02-08 11:59:33 +01:00
|
|
|
import sys
|
|
|
|
|
2020-06-04 20:46:40 +02:00
|
|
|
from dcim.models import Device
|
|
|
|
from ipam.models import IPAddress
|
|
|
|
from startup_script_utils import load_yaml
|
2021-02-08 11:59:33 +01:00
|
|
|
from virtualization.models import VirtualMachine
|
|
|
|
|
2020-06-04 20:46:40 +02:00
|
|
|
|
|
|
|
def link_primary_ip(assets, asset_model):
|
2021-02-08 11:59:33 +01:00
|
|
|
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}
|
|
|
|
print(f"⚠️ IP Address '{query[field]}' not found")
|
|
|
|
|
|
|
|
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])
|
|
|
|
print(f"🔗 Define primary IP '{params[field].address}' on '{asset.name}'")
|
|
|
|
asset.save()
|
|
|
|
|
|
|
|
|
|
|
|
devices = load_yaml("/opt/netbox/initializers/devices.yml")
|
|
|
|
virtual_machines = load_yaml("/opt/netbox/initializers/virtual_machines.yml")
|
2020-06-04 20:46:40 +02:00
|
|
|
|
|
|
|
optional_assocs = {
|
2021-02-08 11:59:33 +01:00
|
|
|
"primary_ip4": (IPAddress, "address"),
|
|
|
|
"primary_ip6": (IPAddress, "address"),
|
2020-06-04 20:46:40 +02:00
|
|
|
}
|
|
|
|
|
2020-12-18 22:06:08 +01:00
|
|
|
if devices is None and virtual_machines is None:
|
|
|
|
sys.exit()
|
2021-01-19 19:54:52 +01:00
|
|
|
if devices is not None:
|
2021-02-08 11:59:33 +01:00
|
|
|
link_primary_ip(devices, Device)
|
2021-01-19 19:54:52 +01:00
|
|
|
if virtual_machines is not None:
|
2021-02-08 11:59:33 +01:00
|
|
|
link_primary_ip(virtual_machines, VirtualMachine)
|