Signed-off-by: Georg Pfuetzenreuter <mail@georg-pfuetzenreuter.net>
This commit is contained in:
parent
03da60604e
commit
ed427955c3
77
bin/rolesyncer.py
Executable file
77
bin/rolesyncer.py
Executable file
@ -0,0 +1,77 @@
|
|||||||
|
#!/usr/bin/python3
|
||||||
|
|
||||||
|
import os
|
||||||
|
import pynetbox
|
||||||
|
import roles
|
||||||
|
|
||||||
|
if not 'NB_HOST' in os.environ or not 'NB_TOKEN' in os.environ:
|
||||||
|
print('Pass NB_HOST and NB_TOKEN as environment variables.')
|
||||||
|
import sys
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
host = os.environ['NB_HOST']
|
||||||
|
token = os.environ['NB_TOKEN']
|
||||||
|
|
||||||
|
# unlikely to ever change, hence hardcoding the field_id. otherwise we could filter custom_fields for the name 'salt_roles'.
|
||||||
|
field_id = 1
|
||||||
|
|
||||||
|
def connect(host, token):
|
||||||
|
netbox = pynetbox.api(host, token)
|
||||||
|
return(netbox)
|
||||||
|
|
||||||
|
def query_nb(netbox, pk):
|
||||||
|
try:
|
||||||
|
field = netbox.extras.custom_fields.get(pk)
|
||||||
|
except pynetbox.RequestError as myerr:
|
||||||
|
if myerr.req_status_code == 404:
|
||||||
|
print('Custom field not found')
|
||||||
|
raise
|
||||||
|
return(field)
|
||||||
|
|
||||||
|
def get_nb(field):
|
||||||
|
choices = field.choices
|
||||||
|
if not choices:
|
||||||
|
return(None)
|
||||||
|
if len(choices) > 0:
|
||||||
|
return(choices)
|
||||||
|
|
||||||
|
def get_local():
|
||||||
|
return(roles.get())
|
||||||
|
|
||||||
|
def compare(a, b):
|
||||||
|
a.sort()
|
||||||
|
b.sort()
|
||||||
|
if a == b:
|
||||||
|
return(True)
|
||||||
|
if a != b:
|
||||||
|
return(False)
|
||||||
|
|
||||||
|
def write_nb(field, roles):
|
||||||
|
field.choices = roles
|
||||||
|
try:
|
||||||
|
if field.save():
|
||||||
|
print('Update complete')
|
||||||
|
else:
|
||||||
|
print('Nothing to update')
|
||||||
|
except:
|
||||||
|
raise
|
||||||
|
|
||||||
|
def sync(netbox):
|
||||||
|
field = query_nb(netbox, field_id)
|
||||||
|
roles_local = get_local()
|
||||||
|
roles_nb = get_nb(field)
|
||||||
|
|
||||||
|
if roles_nb is None:
|
||||||
|
print('Roles in NetBox are currently empty')
|
||||||
|
|
||||||
|
is_synced = compare(roles_local, roles_nb)
|
||||||
|
|
||||||
|
if is_synced:
|
||||||
|
print('Roles already in sync')
|
||||||
|
if not is_synced:
|
||||||
|
print('Writing local roles to NetBox ...')
|
||||||
|
write_nb(field, roles_local)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
netbox = connect(host, token)
|
||||||
|
sync(netbox)
|
Loading…
Reference in New Issue
Block a user