Ansible Runner Python Example

Python

Ansible Runner is intended to provide a directly importable and usable API for interfacing with Ansible itself and exposes a few helper interfaces.

The modules center around the Runner object. The helper methods will either return an instance of this object which provides aninterface to the results of executing the Ansible command or a tuple the actual output and error response based on the interface.

Ansible Runner itself is a wrapper around Ansible execution and so adds plugins and interfaces to the system in order to gather extra information andprocess/store it for use later.

  1. Like the previous example, we do not need any functions like combine to add a new element to list (or) array, this can be simply done with the + plus sign. Other useful references and examples on Ansible Dictionaries. How to process (or) iterate through the ansible dictionary; A real-time example of a complex Nested List and Dictionaries of.
  2. The following are 17 code examples for showing how to use ansible.playbook.play.Play.These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

Helper Interfaces¶

Ansible, like Puppet and Chef, sports a declarative, domain-specific language, but in contrast to them, Ansible follows a “push-based” method. That means that as long as you have Python installed, and you have an SSH server running on the hosts you wish to configure, you can run Ansible with no problem. Def runplaybook(self, playbookpath,extravars=None): ' run ansible palybook ' try: # if self.redisKey:self.callback = PlayBookResultsCollectorToSave(self.redisKey,self.logId) self.callback = PlayBookResultsCollector if extravars:self.variablemanager.extravars = extravars executor = PlaybookExecutor( playbooks=playbookpath, inventory=self.inventory.

The helper interfaces provides a quick way of supplying the recommended inputs in order to launch a Runner process. These interfaces also allow overriding and providing inputs beyond the scope of what the standalone or container interfacessupport. You can see a full list of the inputs in the linked module documentation.

run() helper function¶

ansible_runner.interface.run()

When called, this function will take the inputs (either provided as direct inputs to the function or from the Runner Input Directory Hierarchy), and execute Ansible. It will run in theforeground and return the Runner object when finished.

run_async() helper function¶

ansible_runner.interface.run_async()

Takes the same arguments as ansible_runner.interface.run() but will launch Ansible asynchronously and return a tuple containingthe thread object and a Runner object. The Runner object can be inspected during execution.

run_command() helper function¶

ansible_runner.interface.run_command()

When called, this function will take the inputs (either provided as direct inputs to the function or from the Runner Input Directory Hierarchy), and execute the command passed eitherlocally or within an container based on the parameters passed. It will run in the foreground and return a tuple of output and error response when finished. While runningthe within container image command the current local working diretory will be volume mounted within the container, in addition to this for any of ansible command lineutilities the inventory, vault-password-file, private-key file path will be volume mounted if provided in the cmdline_args parameters.

run_command_async() helper function¶

ansible_runner.interface.run_command_async()

Takes the same arguments as ansible_runner.interface.run_command() but will launch asynchronously and return a tuple containingthe thread object and a Runner object. The Runner object can be inspected during execution.

get_plugin_docs() helper function¶

ansible_runner.interface.get_plugin_docs()

When called, this function will take the inputs, and execute the ansible-doc command to return the either the plugin-docs or playbook snippet for the passedlist of plugin names. The plugin docs can be fetched either from locally installed plugins or from within an container image based on the parameters passed.It will run in the foreground and return a tuple of output and error response when finished. While running the command within the container the current localworking diretory will be volume mounted within the container.

get_plugin_docs_async() helper function¶

ansible_runner.interface.get_plugin_docs_async()

Takes the same arguments as ansible_runner.interface.get_plugin_docs_async() but will launch asynchronously and return a tuple containingthe thread object and a Runner object. The Runner object can be inspected during execution.

get_plugin_list() helper function¶

ansible_runner.interface.get_plugin_list()

When called, this function will take the inputs, and execute the ansible-doc command to return the list of installed plugins. The installed plugin can be fetchedeither from local environment or from within an container image based on the parameters passed. It will run in the foreground and return a tuple of output and errorresponse when finished. While running the command within the container the current local working diretory will be volume mounted within the container.

get_inventory() helper function¶

ansible_runner.interface.get_inventory()

When called, this function will take the inputs, and execute the ansible-inventory command to return the inventory releated information based on the action.If action is list it will return all the applicable configuration options for ansible, for host action it will return informationof a single host andf for graph action it will return the inventory. The exectuin will be in the foreground and return a tuple of output and errorresponse when finished. While running the command within the container the current local working diretory will be volume mounted within the container.

get_ansible_config() helper function¶

ansible_runner.interface.get_ansible_config()

When called, this function will take the inputs, and execute the ansible-config command to return the Ansible configuration releated information based on the action.If action is list it will return all the hosts related information including the host and group variables, for dump action it will return the enitre active configurationand it can be customized to return only the changed configuration value by settingg the only_changed boolean parameter to True. For view action it will return theview of the active configuration file. The exectuin will be in the foreground and return a tuple of output and error response when finished.While running the command within the container the current local working diretory will be volume mounted within the container.

The Runner object¶

The Runner object is returned as part of the execution of Ansible itself. Since it wraps both execution and outputit has some helper methods for inspecting the results. Other than the methods and indirect properties, the instance of the object itself contains two directproperties:

Ansible Runner Python Example
  • rc will represent the actual return code of the Ansible process
  • status will represent the state and can be one of:
    • unstarted: This is a very brief state where the Runner task has been created but hasn’t actually started yet.
    • successful: The ansible process finished successfully.
    • failed: The ansible process failed.
Python

Runner.stdout

The Runner object contains a property ansible_runner.runner.Runner.stdout which will return an open filehandle containing the stdout of the Ansible process.

Runner.stderr

When the runner_mode is set to subprocess the Runner object uses a property ansible_runner.runner.Runner.stderr whichwill return an open file handle containing the stderr of the Ansible process.

Runner.events

ansible_runner.runner.Runner.events is a generator that will return the Playbook and Host Events as Python dict objects.

Runner.stats

ansible_runner.runner.Runner.stats is a property that will return the final playbookstats event from Ansible in the form of a Python dict

Runner.host_events

ansible_runner.runner.Runner.host_events() is a method that, given a hostname, will return a list of only Ansible event data executed on that Host.

Ansible Runner Python Example Program

Runner.get_fact_cache

ansible_runner.runner.Runner.get_fact_cache() is a method that, given a hostname, will return a dictionary containing the Facts stored for that host during execution.

Runner.event_handler

A function passed to __init__ of Runner, this is invoked every time an Ansible event is received. You can use this toinspect/process/handle events as they come out of Ansible. This function should return True to keep the event, otherwise it will be discarded.

Runner.cancel_callback

A function passed to __init__ of Runner, and to the ansible_runner.interface.run() interface functions.This function will be called for every iteration of the ansible_runner.interface.run() event loop and should return Trueto inform Runner cancel and shutdown the Ansible process or False to allow it to continue.

Runner.finished_callback

A function passed to __init__ of Runner, and to the ansible_runner.interface.run() interface functions.This function will be called immediately before the Runner event loop finishes once Ansible has been shut down.

Runner.status_handler

A function passed to __init__ of Runner and to the ansible_runner.interface.run() interface functions.This function will be called any time the status changes, expected values are:

  • starting: Preparing to start but hasn’t started running yet
  • running: The Ansible task is running
  • canceled: The task was manually canceled either via callback or the cli
  • timeout: The timeout configured in Runner Settings was reached (see env/settings - Settings for Runner itself)
  • failed: The Ansible process failed

Usage examples¶

Providing custom behavior and inputs¶

TODO

The helper methods are just one possible entrypoint, extending the classes used by these helper methods can allow a lot more custom behavior and functionality.

Show:

  • How RunnerConfig is used and how overriding the methods and behavior can work
  • Show how custom cancel and status callbacks can be supplied.

Note

This module is part of ansible-core and included in all Ansibleinstallations. In most cases, you can use the short module namescript even without specifying the collections: keyword.However, we recommend you use the FQCN for easy linking to the moduledocumentation and to avoid conflicting with other collections that may havethe same module name.

  • The script module takes the script name followed by a list of space-delimited arguments.

  • Either a free form command or cmd parameter is required, see the examples.

  • The local script at path will be transferred to the remote node and then executed.

  • The given script will be processed through the shell environment on the remote node.

  • This module does not require python on the remote system, much like the ansible.builtin.raw module.

  • This module is also supported for Windows targets.

Note

This module has a corresponding action plugin.

ParameterChoices/DefaultsComments
chdir
string
Change into this directory on the remote node before running the script.
cmd
string
Path to the local script to run followed by optional arguments.
creates
string
A filename on the remote node, when it already exists, this step will not be run.
decrypt
boolean
    Choices:
  • no
  • yes
This option controls the autodecryption of source files using vault.
executable
string
Name or path of a executable to invoke the script with.
free_form
string
Path to the local script file followed by optional arguments.
removes
string
A filename on the remote node, when it does not exist, this step will not be run.

Note

Ansible Runner Python Example
  • It is usually preferable to write Ansible modules rather than pushing scripts. Convert your script to an Ansible module for bonus points!

  • The ssh connection plugin will force pseudo-tty allocation via -tt when scripts are executed. Pseudo-ttys do not have a stderr channel and all stderr is sent to stdout. If you depend on separated stdout and stderr result keys, please switch to a copy+command set of tasks instead of using script.

  • If the path to the local script contains spaces, it needs to be quoted.

  • This module is also supported for Windows targets.

  • Does not support check_mode.

See also

ansible.builtin.shell

The official documentation on the ansible.builtin.shell module.

Ansible Python Api Example

ansible.windows.win_shell

The official documentation on the ansible.windows.win_shell module.

Authors

Ansible Runner Python Example Pdf

  • Ansible Core Team

  • Michael DeHaan