#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 -v "#"
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):
        f = 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



最后附一张大神做的图片

3.ansible1.7.2 callback插件获取硬件信息并插入到数据库中_第1张图片