use first capture group in regex

This commit is contained in:
Solvik Blum 2019-08-04 19:51:36 +02:00
parent d90eac3fe6
commit 9f0db28ed8
No known key found for this signature in database
GPG key ID: CC12B3DC262B6C47
4 changed files with 12 additions and 11 deletions

View file

@ -3,8 +3,10 @@ netbox:
token: supersecrettoken token: supersecrettoken
datacenter_location: datacenter_location:
# driver_file: /opt/netbox_driver_dc.py driver: "cmd:cat /etc/qualification | tr [a-z] [A-Z]"
driver: file:/etc/qualification regex: "DATACENTER: (?P<datacenter>[A-Za-z0-9]+)"
regex: "datacenter: (?P<datacenter>[A-Za-z0-9]+)"
# driver: 'cmd:lldpctl' # driver: 'cmd:lldpctl'
# regex = 'SysName: .*\.(?P<datacenter>[A-Za-z0-9]+)' # regex: 'SysName: .*\.([A-Za-z0-9]+)'
#
# driver: "file:/tmp/datacenter"
# regex: "(.*)"

View file

@ -10,7 +10,7 @@ class Datacenter():
This class is used to guess the datacenter in order to push the information This class is used to guess the datacenter in order to push the information
in Netbox for a `Device` in Netbox for a `Device`
A driver takes a `value` and evaluates a regex with a `named group`: `datacenter`. A driver takes a `value` and evaluates a regex with a `capture group`.
There's embeded drivers such as `file` or `cmd` which read a file or return the There's embeded drivers such as `file` or `cmd` which read a file or return the
output of a file. output of a file.
@ -20,7 +20,7 @@ class Datacenter():
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.driver = DATACENTER_LOCATION.split(':')[0] self.driver = DATACENTER_LOCATION.split(':')[0]
self.driver_value = DATACENTER_LOCATION.split(':')[1] self.driver_value = ':'.join(DATACENTER_LOCATION.split(':')[1:])
self.driver_file = DATACENTER_LOCATION_DRIVER_FILE self.driver_file = DATACENTER_LOCATION_DRIVER_FILE
if self.driver_file: if self.driver_file:

View file

@ -5,7 +5,6 @@ import subprocess
def get(value, regex): def get(value, regex):
output = subprocess.getoutput(value) output = subprocess.getoutput(value)
r = re.search(regex, output) r = re.search(regex, output)
if r: if r and len(r.groups()) > 0:
result = r.group('datacenter') return r.groups()[0]
return result
return None return None

View file

@ -4,6 +4,6 @@ import re
def get(value, regex): def get(value, regex):
for line in open(value, 'r'): for line in open(value, 'r'):
r = re.search(regex, line) r = re.search(regex, line)
if r: if r and len(r.groups()) > 0:
return r.group('datacenter') return r.groups()[0]
return None return None