【问题标题】:Ansible - putting facts in SQLite via CallbackAnsible - 通过回调将事实放入 SQLite
【发布时间】:2016-06-09 08:59:00
【问题描述】:

使用 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 中没有写入任何内容。

【问题讨论】:

  • 提供的链接中的原始代码使用log 函数而不是runner_on_ok 方法中的“打印”。 log函数实际上将数据写入sqlite。
  • 编辑了原帖,log(res, host) 不向数据库中添加数据。

标签: python sqlite callback ansible ansible-facts


【解决方案1】:

工作代码。如果不需要,请删除 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)

【讨论】:

  • 请注意 result.get('ansible_facts', None) 技巧不再适用于 Ansible 2.2。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 2023-02-23
  • 2017-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多