Ansible Runner Python Example

A Python course for the busy ones to learn Python programming. Learn and practice Python by building two complete apps. Starting point simple example ansible playbook. Python oracle database connection and execution sql. Python Runner - 30 examples found. These are the top rated real world Python examples of ansiblerunner.Runner extracted from open source projects. You can rate examples to help us improve the.

  1. Python Example Programs
  2. Python Tutorial
  3. Ansible Runner Python Example Interview
  4. Ansible Runner Python Example Program
  5. Ansible Runner Python Example Program
  6. Python Example Code

In this post, we will learn how to run a single Ansible automation task using an ad hoc command and explain some use cases for ad hoc commands.

Running ad hoc Commands with Ansible

An ad hoc command is a way of executing a single Ansible task quickly, one that you do not need to save to run again later. They are simple, online operations that can be run without writing a playbook. Ad hoc commands are useful for quick tests and changes. For example, you can use an ad hoc command to make sure that a certain line exists in the /etc/hosts file on a group of servers. You could use another ad hoc command to efficiently restart a service on many different machines or to ensure that a particular software package is up-to-date.

Ad hoc commands are very useful for quickly performing simple tasks with Ansible. They do have their limits, and in general, you will want to use Ansible Playbooks to realize the full power of Ansible. In many situations, however, ad hoc commands are exactly the tool you need to perform simple tasks quickly.

Running Ad Hoc Commands

Use the ansible command to run ad hoc commands:

The host-pattern argument is used to specify the managed hosts on which the ad hoc command should be run. It could be a specific managed host or host group in the inventory. You have already seen this used in conjunction with the –list-hosts option, which shows you which hosts are matched by a particular host pattern. You have also already seen that you can use the -i option to specify a different inventory location to use than the default in the current Ansible configuration file.

The -m option takes as an argument the name of the module that Ansible should run on the targeted hosts. Modules are small programs that are executed to implement your task. Some modules need no additional information, but others need additional arguments to specify the details of their operation. The -a option takes a list of those arguments as a quoted string.

Python for loop

One of the simplest ad hoc commands uses the ping module. This module does not do an ICMP ping, but checks to see if you can run Python-based modules on managed hosts. For example, the following ad hoc command determines whether all managed hosts in the inventory can run standard modules:

Performing Tasks with Modules Using Ad Hoc Commands

Modules are the tools that ad hoc commands use to accomplish tasks. Ansible provides hundreds of modules that do different things. You can usually find a tested, special-purpose module that does what you need as part of the standard installation. The ansible-doc -l command lists all modules installed on a system. You can use ansible- doc to view the documentation of particular modules by name, and find information about what arguments the modules take as options. For example, the following command displays documentation for the ping module:

The following is a list of useful modules as examples. Many others exist.

Files modules

  • copy: Copy a local file to the managed host.
  • file: Set permissions and other properties of files.
  • lineinfile: Ensure a particular line is or is not in a file.
  • synchronize: Synchronize content using rsync.

Software package modules

  • package: Manage packages using autodetected package manager native to the operating system.
  • yum: Manage packages using the YUM package manager.
  • apt: Manage packages using the APT package manager.
  • dnf: Manage packages using the DNF package manager.
  • gem: Manage Ruby gems.
  • pip: Manage Python packages from PyPI.

System modules

  • firewalld: Manage arbitrary ports and services using firewalld.
  • reboot: Reboot a machine.
  • service: Manage services.
  • user: Add, remove, and manage user accounts.

Net Tools modules

  • get_url: Download files over HTTP, HTTPS, or FTP.
  • nmcli: Manage networking.

  • uri: Interact with webservices.
  • Most modules take arguments. You can find the list of arguments available for a module in the module’s documentation. Ad hoc commands pass arguments to modules using the -a option. When no argument is needed, omit the -a option from the ad hoc command. If multiple arguments need to be specified, supply them as a quoted space-separated list. For example, the following ad hoc command uses the user module to ensure that the newbie user exists and has UID 4000 on servera.lab.example.com:

    Most modules are idempotent, which means that they can be run safely multiple times, and if the system is already in the correct state, they do nothing. For example, if you run the previous ad hoc command again, it should report no change:

    Ansible Runner Python Example

    Running Arbitrary Commands on Managed Hosts

    The command module allows administrators to run arbitrary commands on the command line of managed hosts. The command to be run is specified as an argument to the module using the -a option. For example, the following command runs the hostname command on the managed hosts referenced by the mymanagedhosts host pattern.

    The previous ad hoc command example returned two lines of output for each managed host. The first line is a status report, showing the name of the managed host that the ad hoc operation ran on, as well as the outcome of the operation. The second line is the output of the command executed remotely using the Ansible command module.

    For better readability and parsing of ad hoc command output, administrators might find it useful to have a single line of output for each operation performed on a managed host. Use the -o option to display the output of Ansible ad hoc commands in a single line format.

    Runner

    The command module allows administrators to quickly execute remote commands on managed hosts. These commands are not processed by the shell on the managed hosts. As such, they cannot access shell environment variables or perform shell operations, such as redirection and piping.

    Note: If an ad hoc command does not specify which module to use with the -m option, Red Hat Ansible Engine uses the command module by default.

    For situations where commands require shell processing, administrators can use the shell module. Like the command module, you pass the commands to be executed as arguments to the module in an ad hoc command. Ansible then executes the command remotely on the managed hosts. Unlike the command module, the commands are processed through a shell on the managed hosts. Therefore, shell environment variables are accessible and shell operations such as redirection and piping are also available for use.

    The following example illustrates the difference between the command and shell modules. If you try to execute the built-in Bash command set with these two modules, it only succeeds with the shell module.

    Both command and shell modules require a working Python installation on the managed host. A third module, raw, can run commands directly using the remote shell, bypassing the module subsystem. This is useful when managing systems that cannot have Python installed (for example, a network router). It can also be used to install Python on a host.

    Note: In most circumstances, it is a recommended practice that you avoid the command, shell, and raw “run command” modules. Most other modules are idempotent and can perform change tracking automatically. They can test the state of systems and do nothing if those systems are already in the correct state. By contrast, it is much more complicated to use “run command” modules in a way that is idempotent. Depending upon them makes it harder for you to be confident that rerunning an ad hoc command or playbook would not cause an unexpected failure. When a shell or command module runs, it typically reports a CHANGED status based on whether it thinks it affected machine state. There are times when “run command” modules are valuable tools and a good solution to a problem. If you do need to use them, it is probably best to try to use the command module first, resorting to shell or raw modules only if you need their special features.

    Configuring Connections for Ad Hoc Commands

    The directives for managed host connections and privilege escalation can be configured in the Ansible configuration file, and they can also be defined using options in ad hoc commands. When defined using options in ad hoc commands, they take precedence over the directive configured in the Ansible configuration file. The following table shows the analogous command-line options for each configuration file directive.

    CONFIGURATION FILE DIRECTIVES COMMAND-LINE OPTION
    inventory -i
    remote_user -u
    become –become, -b
    become_method–become-method
    become_user –become-user
    become_ask_pass–ask-become-pass, -K

    Before configuring these directives using command-line options, their currently defined values can be determined by consulting the output of ansible –help.

    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.

    Python Example Programs

    Helper Interfaces¶

    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¶

    Python Tutorial

    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()

    Python

    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:

    • 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.

    Ansible Runner Python Example Interview

    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.

    Ansible Runner Python Example Program

    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.

    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

    Ansible Runner Python Example Program

    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

    Python

    Python Example Code

    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.

    Comments are closed.