Ansible callbacks plugin 筆記

http://rfyiamcool.blog.51cto.com/1030776/1440624

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/

 

https://github.com/ansible/ansible/tree/devel/plugins/callbacks

http://docs.ansible.com/developing_plugins.html

這個是把ansible的執行結果記錄下來,官網提供log,mail等方式。

 

http://jpmens.net/2012/09/11/watching-ansible-at-work-callbacks/

這個哥們把它寫到sqlite裏了。

 

lib/ansible/callback_plugins/inventory.py

 

import os
import time
import sqlite3

dbname = '/etc/ansible/setup.db'
TIME_FORMAT='%Y-%m-%d %H:%M:%S'

try:
    con = sqlite3.connect(dbname)
    cur = con.cursor()
except:
    pass

def log(host, data):

    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):
        log(host, res)

然後導出到csv文件

#!/bin/sh

sqlite3 /etc/ansible/setup.db <<EOF
.headers on
.mode csv
.output setup.csv
SELECT * FROM inventory;
EOF

http://stackoverflow.com/questions/25086586/better-way-of-merging-two-json-strings-in-python-for-ansible-callback-plugin

json_log

 

res = {"cmd": "echo \"Hello World\" ", "end": "2014-08-01 19:32:38.714584",  "stdout": "Hello World", "changed": True, "start": "2014-08-01 19:32:38.707510", "delta": "0:00:00.007074", "stderr": "", "rc": 0, "invocation": {"module_name": "shell", "module_args": "echo \"Hello World\""}}

 

def json_log(res, host):
    if isinstance(res,dict) and 'verbose_override' not in res: 
           res.update({"host": host})       
           combined_json  = JSONEncoder().encode(res)
           print(combined_json)

In [73]: json_log(res,"centos")
{"cmd": "echo \"Hello World\" ", "end": "2014-08-01 19:32:38.714584", "stdout": "Hello World", "changed": true, "rc": 0, "start": "2014-08-01 19:32:38.707510", "host": "centos", "stderr": "", "delta": "0:00:00.007074", "invocation": {"module_name": "shell", "module_args": "echo \"Hello World\""}}

 

 

//mysql 入庫,代碼未經測試

 

USE `ansible`;
 

    DROP TABLE IF EXISTS `ansible_callbacks`;

    CREATE TABLE `ansible_callbacks` (

          
      `hosts` varchar(50) NOT NULL,

      `cmd` varchar(50) NOT NULL,

      `start` datetime() NOT NULL,

      `end` datetime() NOT NULL,

      `delta` varchar(255) NOT NULL,

      `changed` varchar(10) NOT NULL,

      `stdout` varchar(50),

      `stderr` varchar(50),
      
      `invocation` mediumtext NOT NULL

          
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;


import sys

import json

import time

import MySQLdb

 

try:

    import MySQLdb

    HAS_MYSQL = True

except ImportError:

    HAS_MYSQL = False

 

def mysql_callback(host, res):


       res.update({"host":host})

       conn=MySQLdb.connect(host='localhost',user='root',passwd='mysqlpw',db='ansible',

                            port=3306)

       cursor=conn.cursor()

       sql = '''INSERT INTO `ansible_callbacks`(`host`,`cmd`,`start`,`end`,`delta`,`changed`,'stdout',

              `stderr`, `invocation`)

             VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)'''


       cursor.execute(sql % (str(json.dumps(res['host'])),str(json.dumps(res['cmd'])),

                      str(json.dumps(res['start'])),str(json.dumps(res['end'])),

str(json.dumps(res['delta'])),str(json.dumps(res['changed'])),str(json.dumps(res['stdout'])),

                     str(json.dumps(res['stderr'])),str(json.dumps(res['invocation']))))

 


       conn.commit()

       cursor.close()

       conn.close()

class CallbackModule(object):
    def runner_on_ok(self, host, res):
        mysql_callback(host, res)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章