Search code examples
pythonansibleansible-inventory

Ansible runs all task on local in spite of fetching the proper inventory through InventoryManager


I am using the ansible python sdk to run a play from a source dictionary. I have pointed it to an inventory host file which looks like this:

[k8]
K8master ansible_port=22 ansible_host=172.20.100.22

But when I run the python task it executes everything on localhost. I have tried changing connection='local' to connection='ssh' but then the modules just fail. I have also tried passing the IP directly in hosts of the playbook dict. What am I missing?

This is the python file.

def ansible_workflow(request):
    data = request.data
    context.CLIARGS = ImmutableDict(connection='local', module_path=['/to/mymodules'], forks=10, become=None,
                                    become_method=None, become_user=None, check=False, diff=False)

    loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
    passwords = dict(vault_pass='secret')
    results_callback = ResultCallback()
    inventory = InventoryManager(loader=loader, sources="path/to/hosts")
    variable_manager = VariableManager(loader=loader, inventory=inventory)
        roles = get_roles(item)
        vars_list = [
            {'vars_that_i_use_in_roles': somevar},
        ]

        play_source =  dict(
                name = "Ansible Play",
                hosts = 'k8',
                gather_facts = 'yes',
                vars = vars_list,
                roles = roles
            )
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
    # play._tqm._stdout_callback = ResultCallback()
    # execute_playbook(play_source, extra_vars_dict={})
    tqm = None
    try:
        tqm = TaskQueueManager(
                  inventory=inventory,
                  variable_manager=variable_manager,
                  loader=loader,
                  passwords=passwords,
                  stdout_callback=results_callback,
              )
        result = tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()

        # Remove ansible tmpdir
        shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

Solution

  • Just found out what I was missing. For all the blind people like me I'll leave the answer here:

    I had mentioned connection as local, should have been ssh. And the ssh plugin fails without a verbosity

    context.CLIARGS = ImmutableDict(connection='ssh', module_path=['/to/mymodules'], forks=10, become=None,
                                    become_method=None, become_user=None, check=False, diff=False, verbosity=2)