yaml2json 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.1"
  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('datafile')
  24. options = parser.parse_args()
  25. data = {'data': []}
  26. if os.path.exists(options.datafile):
  27. try:
  28. with open(options.datafile, encoding='utf-8') as f:
  29. datayml = yaml.safe_load(f)
  30. if datayml is not None:
  31. for section in datayml:
  32. localdata = {
  33. '{#KEY}': section,
  34. }
  35. for k in datayml[section]:
  36. localdata['{#%s}' % (k.upper())] = datayml[section][k]
  37. data['data'].append(localdata)
  38. except Exception as e:
  39. if not options.debug:
  40. print('Exception raised (use --debug option to get more info): %s' % (e), file=sys.stderr)
  41. else:
  42. print('Exception raised: %s' % (e), file=sys.stderr)
  43. traceback.print_exc(file=sys.stderr)
  44. print('ZBX_NOTSUPPORTED')
  45. sys.exit(-1)
  46. print(json.dumps(data, indent=4))
  47. # }}}
  48. # {{{ __main__
  49. if __name__ == "__main__":
  50. main()
  51. # }}}
  52. # vim: foldmethod=marker foldlevel=0 foldenable