From ed427955c3bf5561413664caa16e4fa14041e471 Mon Sep 17 00:00:00 2001 From: Georg Pfuetzenreuter Date: Sat, 21 Jan 2023 21:45:25 +0100 Subject: [PATCH] Add rolesyncer script Signed-off-by: Georg Pfuetzenreuter --- bin/rolesyncer.py | 77 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100755 bin/rolesyncer.py diff --git a/bin/rolesyncer.py b/bin/rolesyncer.py new file mode 100755 index 0000000..4761e42 --- /dev/null +++ b/bin/rolesyncer.py @@ -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)