Jonathan Apodaca
Jonathan Apodaca

Reputation: 5808

Custom Ansible Callback not receiving group_vars/host_vars

I have a custom ansible callback that I am writing:

class CallbackModule(CallbackBase):
    CALLBACK_VERSION = 2.0
    CALLBACK_TYPE = 'aggregate'
    CALLBACK_NAME = 'my_callback'

    def v2_runner_on_ok(self, result):
        print("v2_runner_on_ok")
        import pdb; pdb.set_trace()
        result._host.groups[0].get_vars()

When I inspect the contents of result._host.groups[0].get_vars(), it is returning {}, which is not what I expect. I have verified that the host is receiving group_vars (by placing a debug task in my playbook and printing out the expected var). So my question is, why does the callback not receive the group_vars for the host?

On another equally strange note, the host_vars are not commuted to my callback plugin either. It would seem that the only vars that trickle into my plugin are the ones defined in the inventory file, and some magic vars.

Upvotes: 2

Views: 1965

Answers (2)

techraf
techraf

Reputation: 68629

You are accessing variables under ansible.inventory class hence you get only those defined in the inventory.

If you want to access other variables, you need to go through the play's variable manager:

def v2_playbook_on_play_start(self, play):
    variable_manager = play.get_variable_manager()
    hostvars = variable_manager.get_vars()['hostvars']

Upvotes: 3

Jonathan Apodaca
Jonathan Apodaca

Reputation: 5808

Excellent @techraf helped me figure this out. I needed to capture the Play's Variable Manager:

class CallbackModule(CallbackBase):
    CALLBACK_VERSION = 2.0
    CALLBACK_TYPE = 'aggregate'
    CALLBACK_NAME = 'is'

    def v2_playbook_on_play_start(self, play):
      self.vm = play.get_variable_manager()

    def v2_runner_on_ok(self, result):
      host_vars = self.vm.get_vars()['hostvars'][result._host.name]
      var_that_i_want = host_vars['var_that_i_want']

Upvotes: 1

Related Questions