yaml2json 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/python3
  2. # coding: utf-8
  3. # {{{ Imports
  4. import os
  5. import sys
  6. import argparse
  7. import yaml
  8. import json
  9. import traceback
  10. # }}}
  11. # {{{ Constants
  12. _NAME = "yaml2json"
  13. _DESC = "Convert yaml data to zabbix json discovery format"
  14. _VERSION = "0.2"
  15. # }}}
  16. # {{{ main()
  17. def main():
  18. parser = argparse.ArgumentParser(prog=_NAME, description=_DESC)
  19. parser.add_argument('-v', '--version', action='version',
  20. version='%(prog)s ' + _VERSION)
  21. parser.add_argument('-d', '--debug', dest='debug', default=False, action='store_true',
  22. help='Print additional debug informations: traceback, etc. (default: no)')
  23. parser.add_argument('datafiles', nargs='+')
  24. options = parser.parse_args()
  25. data = {'data': []}
  26. for datafile in options.datafiles:
  27. if os.path.exists(datafile):
  28. try:
  29. with open(datafile, encoding='utf-8') as f:
  30. datayml = yaml.safe_load(f)
  31. if datayml is not None:
  32. for section in datayml:
  33. localdata = {
  34. '{#KEY}': section,
  35. }
  36. for k in datayml[section]:
  37. localdata['{#%s}' % (k.upper())] = datayml[section][k]
  38. data['data'].append(localdata)
  39. except Exception as e:
  40. if not options.debug:
  41. print('Exception raised (use --debug option to get more info): %s' % (e), file=sys.stderr)
  42. else:
  43. print('Exception raised: %s' % (e), file=sys.stderr)
  44. traceback.print_exc(file=sys.stderr)
  45. print('ZBX_NOTSUPPORTED')
  46. sys.exit(-1)
  47. print(json.dumps(data, indent=4))
  48. # }}}
  49. # {{{ __main__
  50. if __name__ == "__main__":
  51. main()
  52. # }}}
  53. # vim: foldmethod=marker foldlevel=0 foldenable