ansible_runner package — ansible-runner 1.0.4 documentation

# ansible_runner package

## Subpackages

- ansible_runner.callbacks package
  - Submodules
  - ansible_runner.callbacks.awx_display module
  - ansible_runner.callbacks.minimal module
  - Module contents
- ansible_runner.display_callback package
  - Submodules
  - ansible_runner.display_callback.cleanup module
  - ansible_runner.display_callback.display module
  - ansible_runner.display_callback.events module
  - ansible_runner.display_callback.minimal module
  - ansible_runner.display_callback.module module
  - Module contents

## Submodules

## ansible_runner.exceptions module

exception `ansible_runner.exceptions.` `AnsibleRunnerException`

  Bases: `Exception`

  Generic Runner Error

exception `ansible_runner.exceptions.` `CallbackError`

  Bases: `ansible_runner.exceptions.AnsibleRunnerException`

  Exception occurred in Callback

exception `ansible_runner.exceptions.` `ConfigurationError`

  Bases: `ansible_runner.exceptions.AnsibleRunnerException`

  Misconfiguration of Runner

## ansible_runner.interface module

`ansible_runner.interface.` `init_runner`(**kwargs)

  Initialize the Runner() instance

  This function will properly initialize both run() and run_async() functions in the same way and return a value instance of Runner.

  See parameters given to `ansible_runner.interface.run()`

`ansible_runner.interface.` `run`(**kwargs)

  Run an Ansible Runner task in the foreground and return a Runner object when complete.

  Parameters: | private_data_dir (str) – The directory containing all runner metadata needed to invoke the runner module. Output artifacts will also be stored here for later consumption. ident (str) – The run identifier for this invocation of Runner. Will be used to create and name the artifact directory holding the results of the invocation. json_mode (bool) – Store event data in place of stdout on the console and in the stdout file playbook (str or filename or list) – The playbook (either supplied here as a list or string… or as a path relative to `private_data_dir/project`) that will be invoked by runner when executing Ansible. inventory (str or dict or list) – Overridees the inventory directory/file (supplied at `private_data_dir/inventory`) with a specific host or list of hosts. This can take the form of Path to the inventory file in the `private_data_dir` Native python dict supporting the YAML/json inventory structure A text INI formatted string envvars (dict) – Environment variables to be used when running Ansible. Environment variables will also be read from `env/envvars` in `private_data_dir` extravars (dict) – Extra variables to be passed to Ansible at runtime using `-e`. Extra vars will also be read from `env/extravars` in `private_data_dir`. passwords (dict) – A dictionary containing password prompt patterns and response values used when processing output from Ansible. Passwords will also be read from `env/passwords` in `private_data_dir`. settings (dict) – A dictionary containing settings values for the `ansible-runner` runtime environment. These will also be read from `env/settings` in `private_data_dir`. ssh_key (str) – The ssh private key passed to `ssh-agent` as part of the ansible-playbook run. cmdline (str) – Commnad line options passed to Ansible read from `env/cmdline` in `private_data_dir` limit – Matches ansible’s `--limit` parameter to further constrain the inventory to be used verbosity (int) – Control how verbose the output of ansible-playbook is quiet (bool) – Disable all output artifact_dir (str) – The path to the directory where artifacts should live
  Returns: | A `ansible_runner.runner.Runner` object

`ansible_runner.interface.` `run_async`(**kwargs)

  Runs an Ansible Runner task in the background which will start immediately. Returns the thread object and a Runner object.

  This uses the same parameters as `ansible_runner.interface.run()`

  Returns: | A tuple containing a `threading.Thread` object and a `ansible_runner.runner.Runner` object

## ansible_runner.loader module

class `ansible_runner.loader.` `ArtifactLoader`(base_path)

  Bases: `object`

  Handles loading and caching file contents from disk

  This class will load the file contents and attempt to deserialize the contents as either JSON or YAML. If the file contents cannot be deserialized, the contents will be returned to the caller as a string.

  The deserialized file contents are stored as a cached object in the instance to avoid any additional reads from disk for subsequent calls to load the same file.

  `abspath`(path)

    Transform the path to an absolute path

    Args:
      path (string): The path to transform to an absolute path
    Returns:
      string: The absolute path to the file
  `get_contents`(path)

    Loads the contents of the file specified by path

    Args:
      path (string): The relative or absolute path to the file to
        be loaded. If the path is relative, then it is combined with the base_path to generate a full path string
    Returns:
      string: The contents of the file as a string
    Raises:
      ConfigurationError: If the file cannot be loaded
  `isfile`(path)

    Check if the path is a file

    Params path: | The path to the file to check. If the path is relative it will be exanded to an absolute path
    Returns: | boolean

  `load_file`(path, objtype=None, encoding='utf-8')

    Load the file specified by path

    This method will first try to load the file contents from cache and if there is a cache miss, it will load the contents from disk

    Args:

      path (string): The full or relative path to the file to be loaded

      encoding (string): The file contents text encoding

      objtype (object): The object type of the file contents. This
        is used to type check the deserialized content against the contents loaded from disk. Ignore serializing if objtype is string_types
    Returns:
      object: The deserialized file contents which could be either a
        string object or a dict object
    Raises:
      ConfigurationError:

## ansible_runner.runner module

class `ansible_runner.runner.` `Runner`(config, cancel_callback=None, remove_partials=True)

  Bases: `object`

  `event_callback`(event_data)

    Invoked for every Ansible event to collect stdout with the event data and store it for later use

  `events`

    A generator that will return all ansible job events in the order that they were emitted from Ansible

    Example:

    > > {

    > >   “event”:”runner_on_ok”, “uuid”:”00a50d9c-161a-4b74-b978-9f60becaf209”, “stdout”:”ok: [localhost] => {rn ” msg”:”Test!”rn}”, “counter”:6, “pid”:740, “created”:”2018-04-05T18:24:36.096725”, “end_line”:10, “start_line”:7, “event_data”:{

    > >   > “play_pattern”:”all”, “play”:”all”, “task”:”debug”, “task_args”:”msg=Test!”, “remote_addr”:”localhost”, “res”:{

    > >   > > “msg”:”Test!”, “changed”:false, “_ansible_verbose_always”:true, “_ansible_no_log”:false

    > >   > }, “pid”:740, “play_uuid”:”0242ac11-0002-443b-cdb1-000000000006”, “task_uuid”:”0242ac11-0002-443b-cdb1-000000000008”, “event_loop”:null, “playbook_uuid”:”634edeee-3228-4c17-a1b4-f010fdd42eb2”, “playbook”:”test.yml”, “task_action”:”debug”, “host”:”localhost”, “task_path”:”/tmp/demo/project/test.yml:3”

    > >   }

    > }

  classmethod `handle_termination`(pid, args, proot_cmd, is_cancel=True)

    Internal method to terminate a subprocess spawned by pexpect representing an invocation of runner.

    Parameters: | pid – the process id of the running the job. args – the args for the job, i.e., [‘ansible-playbook’, ‘abc.yml’]

    :param proot_cmd the command used to isolate processes i.e., bwrap :param is_cancel: flag showing whether this termination is caused by

    > instance’s cancel_flag.

  `host_events`(host)

    Given a host name, this will return all task events executed on that host

  `run`()

    Launch the Ansible task configured in self.config (A RunnerConfig object), returns once the invocation is complete

  `stats`

    Returns the final high level stats from the Ansible run

    Example:
      {‘dark’: {}, ‘failures’: {}, ‘skipped’: {}, ‘ok’: {u’localhost’: 2}, ‘processed’: {u’localhost’: 1}}
  `stdout`

    Returns an open file handle to the stdout representing the Ansible run

## ansible_runner.runner_config module

class `ansible_runner.runner_config.` `RunnerConfig`(private_data_dir=None, playbook=None, ident=UUID('3604aa3a-4b39-4a39-9868-807ea999a41a'), inventory=None, limit=None, module=None, module_args=None, verbosity=None, quiet=False, json_mode=False, artifact_dir=None)

  Bases: `object`

  A `Runner` configuration object that’s meant to encapsulate the configuration used by the `ansible_runner.runner.Runner` object to launch and manage the invocation of `ansible` and `ansible-playbook`

  Typically this object is initialized for you when using the standard `run` interfaces in `ansible_runner.interface` but can be used to construct the `Runner` configuration to be invoked elsewhere. It can also be overridden to provide different functionality to the Runner object.

  Example: |

      >>> rc = RunnerConfig(...)
      >>> r = Runner(config=rc)
      >>> r.run()

  `args2cmdline`(*args)
  `generate_ansible_command`()

    Given that the `RunnerConfig` preparation methods have been run to gather the inputs this method will generate the `ansible` or `ansible-playbook` command that will be used by the `ansible_runner.runner.Runner` object to start the process

  `open_fifo_write`(path, data)

    open_fifo_write opens the fifo named pipe in a new thread. This blocks the thread until an external process (such as ssh-agent) reads data from the pipe.

  `prepare`()

    Performs basic checks and then properly invokes

    - prepare_inventory
    - prepare_env
    - prepare_command

    It’s also responsible for wrapping the command with the proper ssh agent invocation and setting early ANSIBLE_ environment variables.

  `prepare_command`()

    Determines if the literal `ansible` or `ansible-playbook` commands are given and if not calls `ansible_runner.runner_config.RunnerConfig.generate_ansible_command()`

  `prepare_env`()

    Manages reading environment metadata files under `private_data_dir` and merging/updating with existing values so the `ansible_runner.runner.Runner` object can read and use them easily

  `prepare_inventory`()

    Prepares the inventory default under `private_data_dir` if it’s not overridden by the constructor.

  `wrap_args_with_ssh_agent`(args, ssh_key_path, ssh_auth_sock=None, silence_ssh_add=False)

    Given an existing command line and parameterization this will return the same command line wrapped with the necessary calls to `ssh-agent`

## ansible_runner.utils module

class `ansible_runner.utils.` `OutputEventFilter`(handle, event_callback, suppress_ansible_output=False, output_json=False)

  Bases: `object`

  File-like object that looks for encoded job events in stdout data.

  `EVENT_DATA_RE` = re.compile('\\x1b\\[K((?:[A-Za-z0-9+/=]+\\x1b\\[\\d+D)+)\\x1b\\[K')
  `close`()
  `flush`()
  `write`(data)

`ansible_runner.utils.` `dump_artifact`(obj, path, filename=None)

  Write the artifact to disk at the specified path

  Args:
    obj (string): The string object to be dumped to disk in the specified
      path. The artifact filename will be automatically created

    path (string): The full path to the artifacts data directory.

    filename (string, optional): The name of file to write the artifact to.
      If the filename is not provided, then one will be generated.
  Returns:
    string: The full path filename for the artifact that was generated

`ansible_runner.utils.` `dump_artifacts`(kwargs)

  Introspect the kwargs and dump objects to disk

`ansible_runner.utils.` `isinventory`(obj)

  Inspects the object and returns if it is an inventory

  Args:
    obj (object): The object to be inspected by this function
  Returns:
    boolean: True if the object is an inventory dict and False if it is not

`ansible_runner.utils.` `isplaybook`(obj)

  Inspects the object and returns if it is a playbook

  Args:
    obj (object): The object to be inspected by this function
  Returns:
    boolean: True if the object is a list and False if it is not

## Module contents