Advertisement
Guest User

Untitled

a guest
May 27th, 2016
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. #import argparse
  4. import datetime
  5. import json
  6. import MySQLdb
  7. #import sys
  8.  
  9. HOST = '127.0.0.1'
  10. USER = 'ansible'
  11. PASSWORD = 'ansible'
  12. DB = 'ansible_inventory'
  13. SQL = """
  14. SELECT hg.group_names, h.inventory_hostname, hd.ansible_hostname, hd.ansible_ssh_host
  15. FROM
  16. HostDetails AS hd, Hosts AS h, HostGroups AS hg
  17. WHERE h.HostId = hd.HostId AND h.HostId = hg.HostId
  18. """
  19.  
  20. class AnsibleMySQL(object):
  21.  
  22. def __init__(self):
  23. self.db_connect()
  24. self.db_query()
  25. # self.define_vars()
  26. self.group_list()
  27. self.display_results()
  28.  
  29. def db_connect(self):
  30. self.con = MySQLdb.connect(HOST, USER, PASSWORD, DB)
  31. self.cur = self.con.cursor()
  32.  
  33. def db_query(self):
  34. try:
  35. self.cur.execute(SQL)
  36. self.rows = self.cur.fetchall()
  37. finally:
  38. self.cur.close()
  39. self.con.close()
  40.  
  41. # def define_vars(self):
  42. # self.columns = [desc[0] for desc in self.cur.description]
  43. # self.groups = list()
  44. # self.hosts = list()
  45. # self.host_vars = list()
  46. # self.results = list()
  47.  
  48. def group_list(self):
  49. self.inventory = {}
  50. for self.row in range(len(self.rows)):
  51. self.group = (self.rows[self.row][0])
  52. self.inventory[self.group] = {
  53. 'hosts': []
  54. }
  55. self.inventory[self.group]['hosts'].append(self.rows[self.row][1])
  56.  
  57. # for self.row in self.rows:
  58. # self.row = dict(zip(self.columns, self.row))
  59. # self.host_vars.append(self.row)
  60.  
  61. def display_results(self):
  62. # print json.dumps({'hosts': self.hosts, '_meta': self._meta},
  63. # default=datetime_handler, indent=2)
  64. # print json.dumps({'groups': self.groups, 'hosts': self.hosts},
  65. # default=datetime_handler, indent=2)
  66. # print ({'hosts': self.hosts})
  67. # print json.dumps(self.results, indent=2)
  68. print json.dumps(self.inventory, indent=2)
  69.  
  70. def datetime_handler(obj):
  71. """
  72. JSON serializer for objects not serializable by default json code
  73. """
  74. if isinstance(obj, datetime.datetime):
  75. return obj.isoformat()
  76. raise TypeError("Unknown type")
  77.  
  78. if __name__ == '__main__':
  79. AnsibleMySQL()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement