|
cat books.txt cxx代表组名
cxx 172.1.1.196 sc_tomcat 8005 8080
sxx 172.1.1.196 sc_tomcat 8006 8081
wxx 172.1.1.196 sc_tomcat 8007 8082
第三种
#从mysql hosts表生成最新的ansible hosts文件
import os
import sys
import commands
import MySQLdb
import json
def Inventory(iplist1):
#不用
inventory = {}
for ip in iplist1:
if ip in dict.iterkeys():
# print ip,dict[ip]
group = dict[ip]
if not group in inventory:
inventory[group] = {
'hosts': []
}
inventory[group]['hosts'].append(ip)
print json.dumps(inventory, indent=4)
def grouplist(conn,file):
inventory = {}
#inventory['local'] = ['127.0.0.1']
cur = conn.cursor()
cur.execute("SELECT ip,env from hosts ORDER BY 1, 2")
for row in cur.fetchall():
group = row[1]
if len(group.split(','))>1:
for i in range(len(group.split(','))):
pgroup = group.split(',')
ip = row[0]
if not pgroup in inventory:
inventory[pgroup] = {
'hosts': []
}
inventory[pgroup]['hosts'].append(ip)
else:
if group is None:
group = 'ungrouped'
if not group in inventory:
inventory[group] = {
'hosts': []
}
inventory[group]['hosts'].append(row[0])
cur.close()
anum = 0
for num in inventory.items():
anum += len(num[1]['hosts'])
print anum
f = open(file, 'w')
f.write(json.dumps(inventory, indent=4))
f.close()
if __name__ == '__main__':
conn = MySQLdb.connect("172.1.1.197", "root", "root", "cmdb")
file = 'mysql_inventory'
grouplist(conn,file) |
|
|