Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- #import argparse
- import datetime
- import json
- import MySQLdb
- #import sys
- HOST = '127.0.0.1'
- USER = 'ansible'
- PASSWORD = 'ansible'
- DB = 'ansible_inventory'
- SQL = """
- SELECT hg.group_names, h.inventory_hostname, hd.ansible_hostname, hd.ansible_ssh_host
- FROM
- HostDetails AS hd, Hosts AS h, HostGroups AS hg
- WHERE h.HostId = hd.HostId AND h.HostId = hg.HostId
- """
- class AnsibleMySQL(object):
- def __init__(self):
- self.db_connect()
- self.db_query()
- # self.define_vars()
- self.group_list()
- self.display_results()
- def db_connect(self):
- self.con = MySQLdb.connect(HOST, USER, PASSWORD, DB)
- self.cur = self.con.cursor()
- def db_query(self):
- try:
- self.cur.execute(SQL)
- self.rows = self.cur.fetchall()
- finally:
- self.cur.close()
- self.con.close()
- # def define_vars(self):
- # self.columns = [desc[0] for desc in self.cur.description]
- # self.groups = list()
- # self.hosts = list()
- # self.host_vars = list()
- # self.results = list()
- def group_list(self):
- self.inventory = {}
- for self.row in range(len(self.rows)):
- self.group = (self.rows[self.row][0])
- self.inventory[self.group] = {
- 'hosts': []
- }
- self.inventory[self.group]['hosts'].append(self.rows[self.row][1])
- # for self.row in self.rows:
- # self.row = dict(zip(self.columns, self.row))
- # self.host_vars.append(self.row)
- def display_results(self):
- # print json.dumps({'hosts': self.hosts, '_meta': self._meta},
- # default=datetime_handler, indent=2)
- # print json.dumps({'groups': self.groups, 'hosts': self.hosts},
- # default=datetime_handler, indent=2)
- # print ({'hosts': self.hosts})
- # print json.dumps(self.results, indent=2)
- print json.dumps(self.inventory, indent=2)
- def datetime_handler(obj):
- """
- JSON serializer for objects not serializable by default json code
- """
- if isinstance(obj, datetime.datetime):
- return obj.isoformat()
- raise TypeError("Unknown type")
- if __name__ == '__main__':
- AnsibleMySQL()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement