add support for a datacenter driver in a separate file

This commit is contained in:
Solvik Blum 2019-08-04 09:48:42 +02:00
parent 8b8cd68ff2
commit 6b24b4b000
No known key found for this signature in database
GPG key ID: CC12B3DC262B6C47
2 changed files with 20 additions and 7 deletions

View file

@ -11,5 +11,6 @@ netbox_instance = pynetbox.api(
)
DATACENTER_LOCATION = config['datacenter_location']['driver']
DATACENTER_LOCATION_REGEX = config['datacenter_location']['regex']
DATACENTER_LOCATION_DRIVER_FILE = config.get('datacenter_location').get('driver_file')
DATACENTER_LOCATION = config.get('datacenter_location').get('driver')
DATACENTER_LOCATION_REGEX = config.get('datacenter_location').get('regex')

View file

@ -1,6 +1,7 @@
import importlib
import importlib.machinery
from netbox_agent.config import DATACENTER_LOCATION, \
from netbox_agent.config import DATACENTER_LOCATION, DATACENTER_LOCATION_DRIVER_FILE, \
DATACENTER_LOCATION_REGEX
@ -10,11 +11,22 @@ class Datacenter():
def __init__(self, *args, **kwargs):
self.driver = DATACENTER_LOCATION.split(':')[0]
self.driver_value = DATACENTER_LOCATION.split(':')[1]
self.driver_file = DATACENTER_LOCATION_DRIVER_FILE
try:
self.driver = importlib.import_module('netbox_agent.drivers.datacenter_' + self.driver)
except ImportError:
raise ImportError("Driver {} doesn't exists".format(self.driver))
if self.driver_file:
try:
# FIXME: Works with Python 3.3+, support older version?
loader = importlib.machinery.SourceFileLoader('driver_file', self.driver_file)
self.driver = loader.load_module()
except ImportError:
raise ImportError("Couldn't import {} as a module".format(self.driver_file))
else:
try:
self.driver = importlib.import_module(
'netbox_agent.drivers.datacenter_{}'.format(self.driver)
)
except ImportError:
raise ImportError("Driver {} doesn't exists".format(self.driver))
def get(self):
return getattr(self.driver, 'get')(self.driver_value, DATACENTER_LOCATION_REGEX)