Ansible Runner: Ansible from Python code

Ansible Runner is a Python module that allows you to run Ansible playbooks from Python code. It offers directly importable and usable API for interfacing with Ansible.

In Python, one way of dealing with Ansible is to just call it using modules such as subprocess or os.system. Ansible Runner offers a more ‘Pythonic way‘ of doing this, by providing a Python API for running Ansible playbooks. It also “exposes a few helper interfaces” which allows you to supply
recommended inputs to launch a Runner process. Here I will review how to run an ad hoc Ansible command and a playbook using Ansible Runner.

ansible_runner.run

Let us start with a simple Ansible ad hoc command. We will use the ping module to ping all hosts in an inventory.yml file from the CLI:

ansible -i inventory.yml all -m ping

The way to do the same with Ansible Runner looks like this:

#!/usr/bin/env python3
import ansible_runner

r = ansible_runner.run(
    inventory='inventory.yml',
    module='ping',
    host_pattern='all'
)

The first thing is to import the ansible_runner module. Then we call the run function and then we can pass the required arguments to replicate the same thing we did with the CLI command. Following the documentation, we selected inventory, module, and host_pattern parameters.

To run a playbook, we have to use the playbook function. The CLI command for that would be:

ansible-playbook -i inventory.yml all playbook.yml

The equivalent Ansible Runner command would be:

#!/usr/bin/env python3
import ansible_runner
    
r = ansible_runner.run(
    inventory='inventory.yml',
    playbook='playbook.yml',
    host_pattern='all',
    extravars={
        'ansible_user': 'user',
        'ansible_password': 'password'
    }
)

By default ansible_runner.run shows the standard output and standard error in the console. This can be turned off by setting the quiet parameter to True. Also, notice that in this case, the extravars parameter takes a dictionary as input. The documentation explains what type of data is expected for each parameter.

ansible_runner.runner.Runner object

The run function returns a Runner object, which we stored in the r variable. Here is a list of the properties of the Runner object:

  • r.status: string with the status of the execution. If the execution was successful, the status will be ‘successful’. If the execution failed, the status will be ‘failed’.
  • r.rc: integer with the return code of the execution. If the execution was successful, the return code will be 0. If the execution failed, the return code will be 1.
  • r.stdout: string with the standard output of the execution.
  • r.stderr: string with the standard error of the execution.

This makes it easy to check if the execution was successful or not:

if r.status == 'successful':
    print('The execution was successful')
else:
    print('The execution failed')
| Theme: UPortfolio