从CMDB动态获取服务器列表,按照Ansible的约定

目标效果:

[root@ansible ~]# python query.py --list
{
"test": [
  "10.1.2.1",
  "10.1.2.2"
],
"www": [
  "1.2.3.4",
  "5.6.7.8"
]
}

[root@ansible ~]# python query.py --host 5.6.7.8
{
  "ansible_group": "www",
  "ansible_host": "5.6.7.8"
}

代码:

[root@ansible ~]# cat query.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
#author: xiaoweige
import json
import pymysql
import argparse
from contextlib import contextmanager
from collections import defaultdict

#todo: parse the given --list without arg but --host '10.1.2.2'
def parse_args():
  parser = argparse.ArgumentParser(description='--list or --host 10.1.2.2')
  parser.add_argument('--list',action='store_true',help='--list without args')
  parser.add_argument('--host',help='--host 10.1.2.2')
  args = parser.parse_args()
  return args
#todo: to dump the dict into json
def to_json(indict):
  return json.dumps(indict,indent=3)
#todo: create a connection to the mysql
@contextmanager
def get_conn(**kwargs):
    conn = pymysql.connect(**kwargs)
    try:
      yield conn
    finally:
      conn.close()

#todo: list all the host
def get_all_list(conn):
  hosts = defaultdict(list)
  with conn as cur:
    cur.execute('select * from yunwei.hosts ' )
    rows = cur.fetchall()
    for no,host,group,user,port in rows:

      hosts[group].append(host)
  return hosts

#todo: query all details of a given hosts
def get_all_detail(conn,host):
  details = {}
  with conn as cur:
    cur.execute("select * from yunwei.hosts where host='{0}'".format(host))
    rows = cur.fetchall()
    for row in rows:
      no,host,group,user,port = row
      details.update(ansible_host=host,ansible_group=group)
  return details
#todo: define main function
def main():
  parser = parse_args()
  with get_conn(host='10.1.1.36',user='root',password='za5121sbsb2az',port=3306) as conn:
    if parser.list:
      hosts = get_all_list(conn)
      print to_json(hosts)
    else:
      details = get_all_detail(conn,parser.host)
      print to_json(details)
if __name__ == '__main__':
  main()

posted @ 2018-03-10 15:48  littlevigra  阅读(214)  评论(0编辑  收藏  举报