Access group vars from callback module in ansible-2.0

Hello,

I’m trying to write callback plugin for ansible.
Below code was working on in ansible-1.9, but it isn’t in ansible-2.0

`

def v2_playbook_on_play_start(self, play):
self.play = play
self.playbook = self.play.playbook
self.inventory = self.playbook.inventory
self.playbook_name, _ = os.path.splitext(os.path.basename(self.playbook.filename))

for g in self.inventory.get_groups():
vars = self.inventory.get_group_vars(g)
print(“… vars for group %s” % g.name)
for v in vars:
print(“%s = %s” % (v, vars.get(v)))

`

Error:

`

[WARNING]: Error when using <bound method CallbackModule.v2_playbook_on_play_start of <…CallbackModule object at 0x7fbf9c8c8c50>>: ‘Play’ object
has no attribute ‘playbook’

`

How should i access group/host variables from callback module in ansible-2.0?

Thanks in advance.

Did you ever figure this out? I’m running into the same issue.

I’m using below hacky approach (found somewere on the internet :wink:

`

def init(self):
self.myvar = None

def v2_playbook_on_play_start(self, play):
var_mgr = play.get_variable_manager()
p_vars = var_mgr.get_vars(loader=play.get_loader())
self.inventory_name = p_vars.get(‘inventory_file’)

initialize

inv = var_mgr._inventory

group vars

self._display.vvvv(‘… group vars’)
for g in inv.get_groups():
self._display.vvvv(‘… group=’ + str(g))
self._display.vvvv(‘… value=’ + str(inv.get_group_variables(g)))
g_vars = inv.get_group_variables(g)

get vars if not defined already (hopping groups are sorted)

if self.myvar is None: self.myvar = g_vars.get(“myvar”, None)

host vars

self._display.vvvv(‘… host vars’)
for h in inv.get_hosts():
self._display.vvvv(‘… host =’ + str(h))
self._display.vvvv(‘… value=’ + str(inv.get_host_vars(h)))
h_vars = inv.get_host_vars(h)
if self.myvar is None: self.myvar = h_vars.get(“myvar”, None)

extra_vars: highest priority

e_vars = var_mgr.extra_vars
self.myvar = e_vars.get(“myvar”, None)

`
This should work with 2.0 - 2.1 (hope ansible will not change it soon, or provide ‘official’ way).