3.ansible1.7.2 callback插件获取硬件信息并插入到数据库中


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#url: http://www.shencan.net/index.php/2014/07/17/ansible-%E6%8F%92%E4%BB%B6%E4%B9%8Bcallback_plugins-%EF%BC%88%E5%AE%9E%E6%88%98%EF%BC%89/
 
cat  / etc / ansible / ansible.cfg|grep callback|grep  - "#"
callback_plugins    =  / usr / share / ansible / plugins / callback
bin_ansible_callbacks  =  True
 
 
cat  / usr / share / ansible / plugins / callback / log_plays.py
#!/usr/bin/env python
# coding:utf8
# 插入到数据库中
import  simplejson
import  sys
import  commands
import  MySQLdb
import  os
import  json
import  time
# import sqlite3
#import redis
import  datetime
from  pymongo  import  MongoClient
 
 
mongoinfo  =  { "host" : "127.0.0.1" , "port" : "27408" , "user" : "root" , "password" : "root" , "dbname" : "ansible_log" }  
 
 
dbname  =  '/tmp/setup.db'
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
 
'''
try:
     con = sqlite3.connect(dbname)
     cur = con.cursor()
except:
     pass
'''
 
def  InsertMDB(values):
     global  mongoinfo
     dbhost  =  mongoinfo[ 'host' ]
     dbport  =  mongoinfo[ 'port' ]
     dbuser  =  mongoinfo[ 'user' ]
     dbpwd   =  mongoinfo[ 'password' ]
     dbname  =  mongoinfo[ 'dbname' ]
     uri  =  'mongodb://%s:%s@%s/%s' % (dbuser,dbpwd,dbhost,dbname)
     #client = MongoClient(uri,safe=False)
     client  =  MongoClient(uri)
     db  =  client.ansible_log
     db.callback.insert(values)
 
class  DB():
     def  __init__( self ):
         self .db  =  MySQLdb.connect( "localhost" "root" "root" "cmdb" )
         self .cursor  =  self .db.cursor()
     def  insert_hosts( self ,ipdict):
             ip  =  ipdict[ 'ip' ]
             hostname  =  ipdict[ 'hostname' ]
             vcpus  =  ipdict[ 'cpu_core' ]
             mem  =  ipdict[ 'memory' ]
             disk_total  =  ipdict[ 'disk' ]
             check_host  =  "select * from hosts_copy where IP = '%s' "  %  (ip)
             flag  =  self .cursor.execute(check_host)
             if  flag ! =  0L :
                 sql  =  "update hosts_copy set hostname = '%s',vcpus = '%s',mem = '%s',disk_total ='%s' where ip = '%s' "  %  (
                     hostname, vcpus, mem, disk_total, ip)
                 try :
                     print  (sql,  '******************' )
                     self .cursor.execute(sql)
                     # 提交到数据库执行
                     self .db.commit()
                     print  ( " '%s' update successfully !" %  (ip)
                 except :
                     # 发生错误时回滚
                     self .db.rollback()
                     print  'Something is wrong !!! '
             else :
                 sql  =  "INSERT INTO hosts_copy(ip,hostname,vcpus,mem,disk_total) VALUES('%s','%s','%s','%s','%s')"  %  (
                     ip, hostname, vcpus, mem, disk_total)
                 print  sql
                 self .cursor.execute(sql)
                 self .db.commit()
 
 
 
 
 
def  log(host, data):
     pass
#    if type(data) == dict:
#        invocation = data.pop('invocation', None)
#        if invocation.get('module_name', None) != 'setup':
#            return
#
#    facts = data.get('ansible_facts', None)
#
#    now = time.strftime(TIME_FORMAT, time.localtime())
#
#    try:
#        # `host` is a unique index
#        cur.execute("REPLACE INTO inventory (now, host, arch, dist, distvers, sys,kernel) VALUES(?,?,?,?,?,?,?);",
#        (
#            now,
#            facts.get('ansible_hostname', None),
#            facts.get('ansible_architecture', None),
#            facts.get('ansible_distribution', None),
#            facts.get('ansible_distribution_version', None),
#            facts.get('ansible_system', None),
#            facts.get('ansible_kernel', None)
#        ))
#        con.commit()
#    except:
#        pass
#
class  CallbackModule( object ):
     def  runner_on_ok( self , host, res):
         if  'stdout'  in  res.keys()  and  res[ 'stdout' ]:
             #print eval(res['stdout'].encode("utf-8"))
             #res_stdout = res['stdout'].encode("utf-8")
             res_stdout  =  res[ 'stdout' ].strip( '\r\n' ).split( '\n' )[ - 1 ]
             try :
                             res_dict  =  eval (res_stdout)
                             db  =  DB()
                             db.insert_hosts(res_dict)
                         except :
                             pass
             
         #host=host=res._host.get_name()
         #r = redis.Redis(host='127.0.0.1', port=6379, db=0) 
         #r.set(host,str(res))
         #f = open('/tmp/11','a')
         #f.write(str(host))
         #f.write(str(res))
         #f.close()
         #log(host, res)
         '''
         now = datetime.datetime.now()
         result = res
         result['time'] = now.strftime(TIME_FORMAT)
         result['status'] = 'ok'
         InsertMDB(result)
         '''
     def  runner_on_failed( self , host, res, ignore_errors = False ):
         =  open ( '/tmp/12' , 'a' )
         f.write( str (host))
         f.write( str (res))
         f.close()
         log(host, res)
 
 
 
说明
1. 插入mongodb
2. 插入mysql
在插入mysql的时候,最基本的log(host, data),可以获取setup的信息,所以在做机器初始化,可以通过setup模块获取,额外的需要自己写脚本,然后得到res


使用ansible-playbook -i hosts main.yml



最后附一张大神做的图片

QQ20140718-1@2x1.png



本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/2049678,如需转载请自行联系原作者

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值