使用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格式返回所有可疑事实.
但是我只需要一小段代码即可将事实输入到sqlite数据库中.
原始来源,但仅适用于ansible 1.x http://jpmens.net/2012/09/11/watching-ansible-at-work-callbacks/
输出没有给出错误,但是在test1.db中没有写入任何内容.
解决方法:
工作代码.如果不需要,请删除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)
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!