Trying to put output in Sqlite3

Hi,

I’m kinda new to Ansible, love the program so far.

I want two facts, hostname and serial number,in a Sqlite database. I’m trying to achieve it with the callback plugin, which is written in Python.

I came across this website and applied his Python code on my machine.
http://jpmens.net/2012/09/11/watching-ansible-at-work-callbacks/

The problem is that the script made by jpmens is for Ansible 1. I’m working with Ansible 2.0.2.0

The code I have for inv.py

import os
import time
import sqlite3

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(object):
def runner_on_ok(self, host, serial):
log(host, serial)

I’m getting the following error message:
" [WARNING]: Failure when attempting to use callback plugin (</etc/ansible/callback_plugin/inv.CallbackModule object at 0x16c5a90>):
‘TaskResult’ object has no attribute ‘get’"

I don’t understand Python quite well. Can anybody pin-point me to my mistake?
Or is there a more simple method to put the values in a sqlite database?

Thanks

Anyone?

Found the answer:

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 test3 (now TEXT, host TEXT UNIQUE, serial TEXT)’)
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 test3 (now, host, serial) VALUES(?,?,?);”,
(
now,
facts.get(‘ansible_hostname’, None),
facts.get(‘ansible_product_serial’, None)
))
con.commit()
except:
pass

Can close.

Callbacks seem a bit overkill for something like this. I would just get the stuff yuu need into variables and then use “shell” or similar to post the data to your datastore, but glad you got it working.