Rework service handling

Allow running playbooks without NetBox access. Mainly to bootstrap
NetBox itself.

Would prefer not to access network from filter plugins, so maybe do
that at some point also.
This commit is contained in:
Timotej Lazar 2024-06-19 13:33:32 +02:00
parent 38c3464279
commit 29598ef4bb
5 changed files with 34 additions and 27 deletions

View file

@ -7,7 +7,8 @@ class FilterModule(object):
'''Various utilities for manipulating NetBox data'''
def __init__(self):
self.nb = pynetbox.api(os.getenv('NETBOX_API'), os.getenv('NETBOX_TOKEN'))
if 'NETBOX_API' in os.environ and 'NETBOX_TOKEN' in os.environ:
self.nb = pynetbox.api(os.getenv('NETBOX_API'), os.getenv('NETBOX_TOKEN'))
def filters(self):
return {
@ -37,11 +38,12 @@ class FilterModule(object):
def allowed_prefixes(self, service):
'''Return a list of allowed IP prefixes for the given service'''
service_data = self.nb.ipam.services.get(service['id']).custom_fields
if service_data['allowed_prefixes']:
yield from self.nb.ipam.prefixes.filter(id=[prefix['id'] for prefix in service_data['allowed_prefixes']])
if service_data['allowed_vlans']:
yield from self.nb.ipam.prefixes.filter(vlan_id=[vlan['id'] for vlan in service_data['allowed_vlans']])
if service_data['allowed_clusters']:
for device in self.nb.dcim.devices.filter(cluster_id=[cluster['id'] for cluster in service_data['allowed_clusters']]):
if 'custom_fields' in service:
service = service['custom_fields']
if prefixes := service.get('allowed_prefixes'):
yield from self.nb.ipam.prefixes.filter(id=[prefix['id'] for prefix in prefixes])
if vlans := service.get('allowed_vlans'):
yield from self.nb.ipam.prefixes.filter(vlan_id=[vlan['id'] for vlan in vlans])
if clusters := service.get('allowed_clusters'):
for device in self.nb.dcim.devices.filter(cluster_id=[cluster['id'] for cluster in clusters]):
yield from self.nb.ipam.ip_addresses.filter(role='loopback', device_id=device.id)