1

I have a playbook that works fine if I run using ansible-playbook command. But I want to execute this playbook from a python script So I created a function in python that takes a path to the inventory file and a path to the playbook file.

from ansible import context
from ansible.cli import CLI
from ansible.module_utils.common.collections import ImmutableDict
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.parsing.dataloader import DataLoader
from ansible.inventory.manager import InventoryManager
from ansible.vars.manager import VariableManager

def runAnsible(inventory, playbook, extra_vars = None):
    print('Running Playbook: ' + playbook)
    loader = DataLoader()
    context.CLIARGS = ImmutableDict(tags={}, listtags=False, listtasks=False, listhosts=False, syntax=False,
                                    module_path=None, forks=100, private_key_file=None,
                                    ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=False,
                                    become_method='sudo', become_user='root', verbosity=True, check=False, start_at_task=None)
    inventory = InventoryManager(loader=loader, sources=(inventory,))
    variable_manager = VariableManager(loader=loader, inventory=inventory, version_info=CLI.version_info(gitinfo=False))
    if extra_vars is not None:
        variable_manager._extra_vars = extra_vars
    pbex = PlaybookExecutor(playbooks=[playbook], inventory=inventory, variable_manager=variable_manager, loader=loader, passwords={})
    return pbex.run()

If I use this function to execute the playbook I get the following error:

Running Playbook: /home/backend/backend-2.0/ansible-playbooks/configure_windows.yml

PLAY [Win Playbook] *************************************************************

TASK [Gathering Facts] *********************************************************
ok: [155.138.136.47]

TASK [Create Installer directory] **********************************************
ok: [155.138.136.47]

TASK [Download the latest installer] *******************************************
An exception occurred during task execution. To see the full traceback, use -vvv. The error was: at <ScriptBlock>, <No file>: line 29
fatal: [155.138.136.47]: FAILED! => {"changed": false, "msg": "Unhandled exception while executing module: Exception calling \"Create\" with \"2\" argument(s): \"Object reference not set to an instance of an object.\""}

PLAY RECAP *********************************************************************
155.138.136.47             : ok=2    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   

Here is the playbook code:

---
- name: Configure Windows
  hosts: all
  become: false
  gather_facts: true
  vars:
    userdir : ansible_user
    ansible_connection: winrm
    ansible_winrm_server_cert_validation: ignore
    ansible_port: 5986
    ansible_transport: Basic
    ansible_winrm_scheme: https
    ansible_winrm_transport: ntlm

  tasks:
   - name: Create Installer directory
     win_file:
      path: C:\abc\xyz
      state: directory
   - name: Download the latest installer
     win_get_url:
      url: https://example.com/msi-installer.msi
      dest: C:\abc\xyz\msi-installer.msi
   - name: Install the latest package
     win_package:
      path: C:\abc\xyz\msi-installer.msi
      state: present
Amarjit Singh
  • 2,068
  • 19
  • 52
  • 1
    Can you please provide your playbook `configure_windows.yml` ? – SmartTom Apr 20 '20 at 14:40
  • @SmartTom I've added the playbook code. This playbook works fine with ansible-playbook command. – Amarjit Singh Apr 20 '20 at 14:50
  • I know but given the error trace, I suspected a syntax error in the playbook. Can you update your python script to run the playbook with `-vvv` ? – SmartTom Apr 20 '20 at 15:35
  • @SmartTom I don't know how to execute playbook with -vvv using the python code. Also, there is no syntax error in the playbook. The playbook works without any error when executed manually with `ansible-playbook` command. – Amarjit Singh Apr 20 '20 at 16:09
  • I think that `verbosity` takes the count of `v`'s [see here](https://github.com/ansible/ansible/blob/fd8b8742730b692a9e715a6a7a922607dcef8821/lib/ansible/cli/__init__.py#L355). So you'd set `verbosity=3` in the `context.CLIARGS` dict. – Tomáš Pospíšek Apr 20 '20 at 16:24
  • What you can also do is to set debug the win_get_url module. You need to add `from ansible.utils.display import Display` to the module and then `Display().warning( "foobar" )` when you want to output/dump stuff. – Tomáš Pospíšek Apr 20 '20 at 16:29
  • The playbook execution output doesn't match up with the playbook code (the `win_stat`, `debug`, and `win_package` tasks never executed). Is there more playbook output you could share? – JR. Apr 21 '20 at 19:26
  • I haven't used ansible's python API very much, but in all of the examples I find, `InventoryManager`'s `sources` argument is a string (similar to the CLI `--limit` argument), not a tuple. – JR. Apr 22 '20 at 20:38

0 Answers0