summaryrefslogtreecommitdiffstats
path: root/roleproxy.py
diff options
context:
space:
mode:
authorGeorg Pfuetzenreuter2023-01-29 19:20:36 +0100
committerGeorg Pfuetzenreuter2023-01-29 19:21:46 +0100
commit4923b43fed1aa3fa8a696cd44b12d0a3ec554f6c (patch)
tree95e42075b23665159b197e54094007086d00ee59 /roleproxy.py
downloadsalt-netbox-roleproxy-4923b43fed1aa3fa8a696cd44b12d0a3ec554f6c.tar.gz
salt-netbox-roleproxy-4923b43fed1aa3fa8a696cd44b12d0a3ec554f6c.tar.bz2
salt-netbox-roleproxy-4923b43fed1aa3fa8a696cd44b12d0a3ec554f6c.zip
Init
Signed-off-by: Georg Pfuetzenreuter <mail@georg-pfuetzenreuter.net>
Diffstat (limited to 'roleproxy.py')
-rwxr-xr-xroleproxy.py53
1 files changed, 53 insertions, 0 deletions
diff --git a/roleproxy.py b/roleproxy.py
new file mode 100755
index 0000000..17ffec3
--- /dev/null
+++ b/roleproxy.py
@@ -0,0 +1,53 @@
+#!/usr/bin/python3
+# This serves a custom "salt_roles" field in NetBox via a HTTP API consumable in Salt top files.
+# Georg Pfuetzenreuter <georg@lysergic.dev>
+
+import flask
+import logging
+import os
+import pynetbox
+from waitress import serve
+
+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']
+
+app = flask.Flask(__name__)
+
+def connect(host, token):
+ netbox = pynetbox.api(host, token)
+ return(netbox)
+
+def get_roles(netbox, name):
+ vm = netbox.virtualization.virtual_machines.filter(name=name)
+ vmroles = {}
+ if len(vm) > 0:
+ vmroles = vm[0].custom_fields['salt_roles']
+ if vmroles is None:
+ vmroles = {}
+ return(200, vmroles)
+ if len(vm) == 0:
+ return(404, None)
+
+@app.route('/roles')
+def query():
+ name = flask.request.args.get('machine')
+ query = get_roles(connect(host, token), name)
+ response = query[0]
+ logger.info(' %s requested roles for %s and received %i', flask.request.remote_addr, name, response)
+ if response == 404:
+ flask.abort(404)
+ elif response == 200:
+ roledict = {'roles': query[1]}
+ return(flask.jsonify(roledict))
+
+if __name__ == '__main__':
+ #app.run(debug=False)
+ logger = logging.getLogger('roleproxy')
+ logger.setLevel(logging.INFO)
+ logger.info('Booting ...')
+ serve(app, host='*', port=4580)