Kevin Kevin - 6 months ago 67
Python Question

Ansible - putting facts in SQLite via Callback

Working with Ansible 2.0.2.0. Trying to put two facts into a sqlite database.
To achieve it, i'm working with a callback plugin. This is the python script so far;

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)


This plugin returns all ansible facts in JSON format.
But I only need a small line of code to input the facts into a sqlite database.

The original source, but only works with ansible 1.x http://jpmens.net/2012/09/11/watching-ansible-at-work-callbacks/

The output gives no error, but nothing is written in the test1.db.

Answer

Working code. Remove CREATE TABLE if not needed.

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)