summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGeorg Pfuetzenreuter2023-01-21 21:45:25 +0100
committerGeorg Pfuetzenreuter2023-01-21 21:45:25 +0100
commited427955c3bf5561413664caa16e4fa14041e471 (patch)
tree6fceff6d0eda458856c5666316ab537f9d8b1870
parent03da60604e755a95c2aaba268725856b3bab0835 (diff)
downloadsalt-ed427955c3bf5561413664caa16e4fa14041e471.tar.gz
salt-ed427955c3bf5561413664caa16e4fa14041e471.tar.bz2
salt-ed427955c3bf5561413664caa16e4fa14041e471.zip
Add rolesyncer script
Signed-off-by: Georg Pfuetzenreuter <mail@georg-pfuetzenreuter.net>
-rwxr-xr-xbin/rolesyncer.py77
1 files changed, 77 insertions, 0 deletions
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)