3

使用 Ansible 2.0.2.0。试图将两个事实放入 sqlite 数据库。为了实现它,我正在使用回调插件。这是迄今为止的python脚本;

import os
import time
import sqlite3
import json

from ansible.plugins.callback import CallbackBase

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

try:
    con = sqlite3.connect(test1)
    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 test2 (now, host, serial) VALUES(?,?,?);",
        (
            now,
            facts.get('ansible_hostname', None),
            facts.get('ansible_product_serial', None)
        ))
        con.commit()
    except:
        pass

class CallbackModule(CallbackBase):
    def runner_on_ok(self, host, res):
    log (res, host)

此插件以 JSON 格式返回所有 ansible 事实。但我只需要一小行代码就可以将事实输入到 sqlite 数据库中。

原始来源,但仅适用于 ansible 1.x http://jpmens.net/2012/09/11/watching-ansible-at-work-callbacks/

输出没有给出错误,但 test1.db 中没有写入任何内容。

4

1 回答 1

4

工作代码。CREATE TABLE如果不需要,请删除。

from ansible.plugins.callback import CallbackBase
import os
import time
import sqlite3

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

try:
    con = sqlite3.connect(dbname)
    cur = con.cursor()
    cur.execute('CREATE TABLE `test` (`now` TEXT, `host` TEXT UNIQUE)')
    con.commit()
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 test (now, host) VALUES(?,?);",
        (
            now,
            facts.get('ansible_hostname', None)
        ))
        con.commit()
    except:
        pass

class CallbackModule(CallbackBase):
    def runner_on_ok(self, host, res):
        log(host, res)
于 2016-06-09T11:10:11.790 回答