Guest User

Untitled

a guest
Jan 21st, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #!/bin/env python
  2.  
  3. import json
  4. import sys
  5.  
  6.  
  7. '''
  8. Description
  9. -----------
  10.  
  11. This cripts converts the output of an Ansible dynamic inventory script to
  12. static INI inventory.
  13.  
  14. Examples of usage
  15. -----------------
  16.  
  17. ./json2ini.py my_inventory.json
  18. script.sh | ./json2ini.py
  19. ./json2ini.py < my_inventory.json
  20. '''
  21.  
  22.  
  23. def usage(kind, text, rc=1):
  24. print("%s: %s\n" % (kind.upper(), text))
  25.  
  26. print("Examples of usage:")
  27. print(" %s <filename> > hosts.ini" % sys.argv[0])
  28. print(" script.sh | %s > hosts.ini" % sys.argv[0])
  29.  
  30. sys.exit(rc)
  31.  
  32.  
  33. def main():
  34. if len(sys.argv) > 1:
  35. # Read data from file
  36. with open(sys.argv[1]) as f:
  37. data = json.load(f)
  38. elif not sys.stdin.isatty():
  39. # Read data from pipe
  40. data_in = sys.stdin.read()
  41. data = json.loads(data_in)
  42. else:
  43. usage("E", "No input data.")
  44.  
  45. for k, v in data.items():
  46. if k == '_meta' and 'hostvars' in v:
  47. # Process hosts
  48. for host, h_vars in v['hostvars'].items():
  49. sys.stdout.write(host)
  50.  
  51. for v_name, v_value in h_vars.items():
  52. sys.stdout.write(" %s=%s" % (v_name, v_value))
  53.  
  54. print("")
  55. else:
  56. kind = 'children'
  57.  
  58. # Process groups
  59. if 'children' in v:
  60. print("[%s:children]" % k)
  61. elif 'hosts' in v:
  62. print("[%s]" % k)
  63. kind = 'hosts'
  64.  
  65. for item in v[kind]:
  66. print(item)
  67.  
  68. print()
  69.  
  70.  
  71. if __name__ == '__main__':
  72. main()
Add Comment
Please, Sign In to add comment