Professional Documents
Culture Documents
8 Developer Documentation 37
Index 65
i
ii
ansible-runner Documentation
Ansible Runner is a tool and python library that helps when interfacing with Ansible directly or as part of another
system whether that be through a container image interface, as a standalone tool, or as a Python module that can be
imported. The goal is to provide a stable and consistent interface abstraction to Ansible. This allows Ansible to be
embedded into other systems that don’t want to manage the complexities of the interface on their own (such as CI/CD
platforms, Jenkins, or other automated tooling).
Ansible Runner represents the modularization of the part of Ansible AWX that is responsible for running ansible and
ansible-playbook tasks and gathers the output from it. It does this by presenting a common interface that doesn’t
change, even as Ansible itself grows and evolves.
Part of what makes this tooling useful is that it can gather its inputs in a flexible way (See Introduction to Ansible
Runner:). It also has a system for storing the output (stdout) and artifacts (host-level event data, fact data, etc) of the
playbook run.
There are 3 primary ways of interacting with Runner
• A standalone command line tool (ansible-runner) that can be started in the foreground or run in the back-
ground asynchronously
• A python module - library interface
Ansible Runner can also be configured to send status and event data to other systems using a plugin interface, see
Sending Runner Status and Events to External Systems.
Examples of this could include:
• Sending status to Ansible AWX
• Sending events to an external logging service
CONTENTS: 1
ansible-runner Documentation
2 CONTENTS:
CHAPTER
ONE
Runner is intended to be most useful as part of automation and tooling that needs to invoke Ansible and consume its
results. Most of the parameterization of the Ansible command line is also available on the Runner command line but
Runner also can rely on an input interface that is mapped onto a directory structure, an example of which can be seen
in the source tree.
Further sections in this document refer to the configuration and layout of that hierarchy. This isn’t the only way to
interface with Runner itself. The Python module interface allows supplying these details as direct module parameters
in many forms, and the command line interface allows supplying them directly as arguments, mimicking the behavior
of ansible-playbook. Having the directory structure does allow gathering the inputs from elsewhere and preparing
them for consumption by Runner, then the tooling can come along and inspect the results after the run.
This is best seen in the way Ansible AWX uses Runner where most of the content comes from the database (and other
content-management components) but ultimately needs to be brought together in a single place when launching the
Ansible task.
This directory contains all necessary inputs. Here’s a view of the demo directory showing an active configuration.
Note that not everything is required. Defaults will be used or values will be omitted if they are not provided.
.
env
envvars
extravars
passwords
cmdline
settings
ssh_key
inventory
hosts
project
test.yml
roles
testrole
defaults
handlers
meta
README.md
tasks
(continues on next page)
3
ansible-runner Documentation
The env directory contains settings and sensitive files that inform certain aspects of the invocation of the Ansible
process, an example of which can be found in the demo env directory. Each of these files can also be represented by
a named pipe providing a bit of an extra layer of security. The formatting and expectation of these files differs slightly
depending on what they are representing.
1.3 env/envvars
Ansible Runner will inherit the environment of the launching shell. This file (which can be in json or yaml format)
represents the environment variables that will be added to the environment at run-time:
---
TESTVAR: exampleval
1.4 env/extravars
Ansible Runner gathers the extra vars provided here and supplies them to the Ansible Process itself. This file can be
in either json or yaml format:
---
ansible_connection: local
test: val
1.5 env/passwords
Warning: We expect this interface to change/simplify in the future but will guarantee backwards compatibility.
The goal is for the user of Runner to not have to worry about the format of certain prompts emitted from Ansible
itself. In particular, vault passwords need to become more flexible.
Ansible itself is set up to emit passwords to certain prompts, these prompts can be requested (-k for example to prompt
for the connection password). Likewise, prompts can be emitted via vars_prompt and also Ansible Vault.
In order for Runner to respond with the correct password, it needs to be able to match the prompt and provide the
correct password. This is currently supported by providing a yaml or json formatted file with a regular expression and
a value to emit, for example:
---
"^SSH password:\\s*?$": "some_password"
"^BECOME password.*:\\s*?$": "become_password"
1.6 env/cmdline
Warning: Current Ansible Runner does not validate the command line arguments passed using this method so
it is up to the playbook writer to provide a valid set of options. The command line options provided by this method
are lower priority than the ones set by Ansible Runner. For instance, this will not override inventory or limit
values.
Ansible Runner gathers command line options provided here as a string and supplies them to the Ansible Process
itself. This file should contain the arguments to be added, for example:
1.7 env/ssh_key
Note: Currently only a single ssh key can be provided via this mechanism but this is set to change soon.
This file should contain the ssh private key used to connect to the host(s). Runner detects when a private key is provided
and will wrap the call to Ansible in ssh-agent.
The settings file is a little different than the other files provided in this section in that its contents are meant to control
Runner directly.
• idle_timeout: 600 If no output is detected from ansible in this number of seconds the execution will be
terminated.
• job_timeout: 3600 The maximum amount of time to allow the job to run for, exceeding this and the execution
will be terminated.
• pexpect_timeout: 10 Number of seconds for the internal pexpect command to wait to block on input before
continuing
• pexpect_use_poll: True Use poll() function for communication with child processes instead of select().
select() is used when the value is set to False. select() has a known limitation of using only up to 1024
file descriptors.
1.6. env/cmdline 5
ansible-runner Documentation
• suppress_output_file: False Allow output from ansible to not be streamed to the stdout or stderr files
inside of the artifacts directory.
• suppress_ansible_output: False Allow output from ansible to not be printed to the screen.
• fact_cache: 'fact_cache' The directory relative to artifacts where jsonfile fact caching will be stored.
Defaults to fact_cache. This is ignored if fact_cache_type is different than jsonfile.
• fact_cache_type: 'jsonfile' The type of fact cache to use. Defaults to jsonfile.
The process isolation settings are meant to control the process isolation feature of Runner.
• process_isolation: False Enable limiting what directories on the filesystem the playbook run has access to.
• process_isolation_executable: bwrap Path to the executable that will be used to provide filesystem iso-
lation.
• process_isolation_path: /tmp Path that an isolated playbook run will use for staging.
• process_isolation_hide_paths: None Path or list of paths on the system that should be hidden from the
playbook run.
• process_isolation_show_paths: None Path or list of paths on the system that should be exposed to the
playbook run.
• process_isolation_ro_paths: None Path or list of paths on the system that should be exposed to the play-
book run as read-only.
These settings instruct Runner to execute Ansible tasks inside a container environment. For information about building
execution environments, see ansible-builder.
To execute Runner with an execution environment:
ansible-runner run --container-image my-execution-environment:latest --process-isolation
-p playbook.yml .
See ansible-runner -h for other container-related options.
1.9 Inventory
The Runner inventory location under the private data dir has the same expectations as inventory provided directly
to ansible itself. It can be either a single file or script or a directory containing static inventory files or scripts. This
inventory is automatically loaded and provided to Ansible when invoked and can be further overridden on the command
line or via the ANSIBLE_INVENTORY environment variable to specify the hosts directly. Giving an absolute path for the
inventory location is best practice, because relative paths are interpreted relative to the current working directory
which defaults to the project directory.
1.10 Project
The Runner project directory is the playbook root containing playbooks and roles that those playbooks can consume
directly. This is also the directory that will be set as the current working directory when launching the Ansible
process.
1.11 Modules
Runner has the ability to execute modules directly using Ansible ad-hoc mode.
1.12 Roles
Runner has the ability to execute Roles directly without first needing a playbook to reference them. This directory
holds roles used for that. Behind the scenes, Runner will generate a playbook and invoke the Role.
This directory will contain the results of Runner invocation grouped under an identifier directory. This identifier
can be supplied to Runner directly and if not given, an identifier will be generated as a UUID. This is how the directory
structure looks from the top level:
.
artifacts
identifier
env
inventory
profiling_data
project
roles
The artifact directory itself contains a particular structure that provides a lot of extra detail from a running or previously-
run invocation of Ansible/Runner:
.
artifacts
37f639a3-1f4f-4acb-abee-ea1898013a25
fact_cache
localhost
job_events
1-34437b34-addd-45ae-819a-4d8c9711e191.json
2-8c164553-8573-b1e0-76e1-000000000006.json
3-8c164553-8573-b1e0-76e1-00000000000d.json
4-f16be0cd-99e1-4568-a599-546ab80b2799.json
5-8c164553-8573-b1e0-76e1-000000000008.json
6-981fd563-ec25-45cb-84f6-e9dc4e6449cb.json
7-01c7090a-e202-4fb4-9ac7-079965729c86.json
rc
(continues on next page)
1.10. Project 7
ansible-runner Documentation
The rc file contains the actual return code from the Ansible process.
The status file contains one of three statuses suitable for displaying:
• success: The Ansible process finished successfully
• failed: The Ansible process failed
• timeout: The Runner timeout (see env/settings - Settings for Runner itself )
The stdout file contains the actual stdout as it appears at that moment.
Runner gathers the individual task and playbook events that are emitted as part of the Ansible run. This is extremely
helpful if you don’t want to process or read the stdout returned from Ansible as it contains much more detail and status
than just the plain stdout. It does some of the heavy lifting of assigning order to the events and stores them in json
format under the job_events artifact directory. It also takes it a step further than normal Ansible callback plugins in
that it will store the stdout associated with the event alongside the raw event data (along with stdout line numbers).
It also generates dummy events for stdout that didn’t have corresponding host event data:
{
"uuid": "8c164553-8573-b1e0-76e1-000000000008",
"parent_uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"counter": 5,
"stdout": "\r\nTASK [debug]␣
˓→*******************************************************************",
"start_line": 5,
"end_line": 7,
"event": "playbook_on_task_start",
"event_data": {
"playbook": "test.yml",
"playbook_uuid": "34437b34-addd-45ae-819a-4d8c9711e191",
"play": "all",
"play_uuid": "8c164553-8573-b1e0-76e1-000000000006",
"play_pattern": "all",
"task": "debug",
"task_uuid": "8c164553-8573-b1e0-76e1-000000000008",
"task_action": "debug",
"task_path": "\/home\/mjones\/ansible\/ansible-runner\/demo\/project\/test.yml:3",
"task_args": "msg=Test!",
"name": "debug",
"is_conditional": false,
"pid": 10640
},
"pid": 10640,
"created": "2018-06-07T14:54:58.410605"
}
If the playbook runs to completion without getting killed, the last event will always be the stats event:
{
"uuid": "01c7090a-e202-4fb4-9ac7-079965729c86",
"counter": 7,
"stdout": "\r\nPLAY RECAP␣
˓→*********************************************************************\r\n\u001b[0;
},
"dark": {
},
"failures": {
},
"ok": {
"localhost,": 2
},
"processed": {
"localhost,": 1
},
"skipped": {
},
"artifact_data": {
},
"pid": 10640
},
"pid": 10640,
"created": "2018-06-07T14:54:58.424603"
}
Note: The Runner module interface presents a programmatic interface to these events that allow getting the final
status and performing host filtering of task events.
If resource profiling is enabled for Runner the profiling_data directory will be populated with a set of files con-
taining the profiling data:
.
profiling_data
0-34437b34-addd-45ae-819a-4d8c9711e191-cpu.json
0-34437b34-addd-45ae-819a-4d8c9711e191-memory.json
0-34437b34-addd-45ae-819a-4d8c9711e191-pids.json
1-8c164553-8573-b1e0-76e1-000000000006-cpu.json
1-8c164553-8573-b1e0-76e1-000000000006-memory.json
1-8c164553-8573-b1e0-76e1-000000000006-pids.json
Each file is in JSON text format. Each line of the file will begin with a record separator (RS), continue with a JSON
dictionary, and conclude with a line feed (LF) character. The following provides an example of what the resource files
may look like. Note that that since the RS and LF are control characters, they are not actually printed below:
• For each task, there will be three files, corresponding to cpu, memory and pid count data.
• Each file contains a set of data points collected over the course of a playbook task.
• If a task executes quickly and the polling rate for a given metric is large enough, it is possible that no profiling
data may be collected during the task’s execution. If this is the case, no data file will be created.
TWO
Ansible Runner requires Python >= 3.9 and is provided from several different locations depending on how you want to
use it.
2.2 Fedora
$ virtualenv env
$ source env/bin/activate
Then install:
$ cd ansible-runner
$ pip install -e .
13
ansible-runner Documentation
THREE
Runner can store event and status data locally for retrieval, it can also emit this information via callbacks provided to
the module interface.
Alternatively Runner can be configured to send events to an external system via installable plugins. Currently, there
are two example plugins are available.
• HTTP Status/Event Emitter Plugin - ansible-runner-http GitHub repo
• ZeroMQ Status/Event Emitter Plugin - ansible-runner-zeromq GitHub repo
Please refer respective repos to configure these plugins.
There are two types of events that are emitted via plugins:
• status events:
These are sent whenever Runner’s status changes (see Runner.status_handler) for example:
{"status": "running", "runner_ident": "XXXX" }
• ansible events:
These are sent during playbook execution for every event received from Ansible (see Playbook and Host Events)
for example:
{"runner_ident": "XXXX", <rest of event structure> }
In order to write your own plugin interface and have it be picked up and used by Runner there are a few things that
you’ll need to do.
• Declare the module as a Runner entrypoint in your setup file (ansible-runner-http has a good example of this):
entry_points=('ansible_runner.plugins': 'modname = your_python_package_name'),
• Implement the status_handler() and event_handler() functions at the top of your package, for example
see ansible-runner-http events.py and the __init__ import at the top of the module package
After installing this, Runner will see the plugin and invoke the functions when status and events are sent. If there are
any errors in your plugin they will be raised immediately and Runner will fail.
15
ansible-runner Documentation
FOUR
The Ansible Runner command line tool can be used as a standard command line interface to Ansible itself but is
primarily intended to fit into automation and pipeline workflows. Because of this, it has a bit of a different workflow
than Ansible itself because you can select between a few different modes to launch the command.
While you can launch Runner and provide it all of the inputs as arguments to the command line (as you do with
Ansible itself), there is another interface where inputs are gathered into a single location referred to in the command
line parameters as private_data_dir. (see Runner Input Directory Hierarchy)
To view the parameters accepted by ansible-runner:
$ ansible-runner --help
Where playbook.yml is the playbook from the /tmp/private/projects directory, and run is the command mode
you want to invoke Runner with
The different commands that runner accepts are:
• run starts ansible-runner in the foreground and waits until the underlying Ansible process completes before
returning
• start starts ansible-runner as a background daemon process and generates a pid file
• stop terminates an ansible-runner process that was launched in the background with start
• is-alive checks the status of an ansible-runner process that was started in the background with start
While Runner is running it creates an artifacts directory (see Runner Artifacts Directory Hierarchy) regardless of
what mode it was started in. The resulting output and status from Ansible will be located here. You can control the
exact location underneath the artifacts directory with the -i IDENT argument to ansible-runner, otherwise a
random UUID will be generated.
17
ansible-runner Documentation
When launching Runner with the run command, as above, the program will stay in the foreground and you’ll see
output just as you expect from a normal Ansible process. Runner will still populate the artifacts directory, as
mentioned in the previous section, to preserve the output and allow processing of the artifacts after exit.
When launching Runner with the start command, the program will generate a pid file and move to the background.
You can check its status with the is-alive command, or terminate it with the stop command. You can find the stdout,
status, and return code in the artifacts directory.
Ansible roles directory can be provided with --roles-path option. Role variables can be passed with --role-vars
at runtime.
Runner supports process isolation. Process isolation creates a new mount namespace where the root is on a tmpfs that
is invisible from the host and is automatically cleaned up when the last process exits. You can enable process isolation
by providing the --process-isolation argument on the command line. Runner as of version 2.0 defaults to using
podman as the process isolation executable, but supports using any executable that is compatible with the bubblewrap
CLI arguments by passing in the --process-isolation-executable argument:
Runner supports various process isolation arguments that allow you to provide configuration details to the process
isolation executable. To view the complete list of arguments accepted by ansible-runner:
$ ansible-runner --help
If you need to be able to execute multiple tasks in parallel that might conflict with each other or if you want to make
sure a single invocation of Ansible/Runner doesn’t pollute or overwrite the playbook content you can give a base path:
Runner will copy the project directory to a temporary directory created under that path, set it as the working directory,
and execute from that location. After running that temp directory will be cleaned up and removed.
The default inventory, if not specified, will be <private_data_dir>/inventory/. All files within this subdirectory
of the private data directory will be processed as potential inventory host files. You may specify a different inventory
using the --inventory option. This value may be one of:
• A file name located within <private_data_dir>/inventory/.
• An absolute or relative path to an alternate inventory file or directory. This path is not required to be inside of
the private data directory.
Examples:
4.9 Outputting json (raw event data) to the console instead of normal
output
Runner supports outputting json event data structure directly to the console (and stdout file) instead of the standard
Ansible output, thus mimicking the behavior of the json output plugin. This is in addition to the event data that’s
already present in the artifact directory. All that is needed is to supply the -j argument on the command line:
Using the command line argument --rotate-artifacts allows you to control the number of artifact directories that
are present. Given a number as the parameter for this argument will cause Runner to clean up old artifact directories.
The default value of 0 disables artifact directory cleanup.
FIVE
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 an interface 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 and process/store it for use later.
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 interfaces support. You can see a full list of the inputs in the linked module documentation.
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 the foreground and return the Runner object when finished.
ansible_runner.interface.run_async()
Takes the same arguments as ansible_runner.interface.run() but will launch Ansible asynchronously and re-
turn a tuple containing the thread object and a Runner object. The Runner object can be inspected during execution.
21
ansible-runner Documentation
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 either locally 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 running the
within container image command the current local working directory will be volume mounted within the container, in
addition to this for any of ansible command line utilities the inventory, vault-password-file, private-key file path will
be volume mounted if provided in the cmdline_args parameters.
ansible_runner.interface.run_command_async()
Takes the same arguments as ansible_runner.interface.run_command() but will launch asynchronously and
return a tuple containing the thread object and a Runner object. The Runner object can be inspected during execution.
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 passed list 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 local
working directory will be volume mounted within the container.
ansible_runner.interface.get_plugin_docs_async()
Takes the same arguments as ansible_runner.interface.get_plugin_docs_async() but will launch asyn-
chronously and return a tuple containing the thread object and a Runner object. The Runner object can be inspected
during execution.
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 fetched either 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 error response when finished.
While running the command within the container the current local working directory will be volume mounted within
the container.
ansible_runner.interface.get_inventory()
When called, this function will take the inputs, and execute the ansible-inventory command to return the inventory
related 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 information of a single host and for graph action it will return the inventory. The
execution 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 directory will be volume mounted within the container.
ansible_runner.interface.get_ansible_config()
When called, this function will take the inputs, and execute the ansible-config command to return the Ansible con-
figuration related 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 entire active configuration and it can be cus-
tomized to return only the changed configuration value by setting the only_changed boolean parameter to True. For
view action it will return the view of the active configuration file. The execution 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 directory will be volume mounted within the container.
ansible_runner.interface.get_role_list()
Version added: 2.2
This function will execute the ansible-doc command to return the list of installed roles that have an argument spec-
ification defined. This data can be fetched from either the local environment or from within a container image based
on the parameters passed. It will run in the foreground and return a tuple of output and error response when finished.
Successful output will be in JSON format as returned from ansible-doc.
ansible_runner.interface.get_role_argspec()
Version added: 2.2
This function will execute the ansible-doc command to return a role argument specification. This data can be fetched
from either the local environment or from within a container image based on the parameters passed. It will run in the
foreground and return a tuple of output and error response when finished. Successful output will be in JSON format as
returned from ansible-doc.
The Runner object is returned as part of the execution of Ansible itself. Since it wraps both execution and output it
has some helper methods for inspecting the results. Other than the methods and indirect properties, the instance of the
object itself contains two direct properties:
• 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.
5.14 Runner.stdout
The Runner object contains a property ansible_runner.runner.Runner.stdout which will return an open file
handle containing the stdout of the Ansible process.
5.15 Runner.stderr
When the runner_mode is set to subprocess the Runner object uses a property ansible_runner.runner.
Runner.stderr which will return an open file handle containing the stderr of the Ansible process.
5.16 Runner.events
ansible_runner.runner.Runner.events is a generator that will return the Playbook and Host Events as Python
dict objects.
5.17 Runner.stats
ansible_runner.runner.Runner.stats is a property that will return the final playbook stats event from An-
sible in the form of a Python dict
5.18 Runner.host_events
5.19 Runner.get_fact_cache
5.20 Runner.event_handler
5.21 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
True to inform Runner cancel and shutdown the Ansible process or False to allow it to continue.
5.22 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.
5.23 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
• successful: The Ansible process succeeded
import ansible_runner
r = ansible_runner.run(private_data_dir='/tmp/demo', playbook='test.yml')
print("{}: {}".format(r.status, r.rc))
# successful: 0
for each_host_event in r.events:
print(each_host_event['event'])
(continues on next page)
5.19. Runner.get_fact_cache 25
ansible-runner Documentation
import ansible_runner
def my_artifacts_handler(artifacts_dir):
# Do something here
print(artifacts_dir)
import ansible_runner
import ansible_runner
def my_event_handler(data):
# Do something here
print(data)
import ansible_runner
r = ansible_runner.run(private_data_dir='/tmp/demo', host_pattern='localhost', module=
˓→'shell', module_args='whoami')
rc.prepare()
(continues on next page)
print("out: {}".format(runner_obj.stdout.read()))
print("err: {}".format(runner_obj.stderr.read()))
print("out: {}".format(out))
print("err: {}".format(err))
print("out: {}".format(out))
print("err: {}".format(err))
# get roles with an arg spec from the `foo.bar` collection in a container
out, err = ansible_runner.get_role_list(collection='foo.bar', process_isolation=True,␣
˓→container_image='network-ee')
print("out: {}".format(out))
print("err: {}".format(err))
# get the arg spec for role `baz` from the locally installed `foo.bar` collection
(continues on next page)
# get the arg spec for role `baz` from the `foo.bar` collection installed in a container
out, err = ansible_runner.get_role_argspec('baz', collection='foo.bar', process_
˓→isolation=True, container_image='network-ee')
print("out: {}".format(out))
print("err: {}".format(err))
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 Runner Config is used and how overriding the methods and behavior can work
• Show how custom cancel and status callbacks can be supplied.
SIX
Note: For an Execution Environments general technology overview and to learn how get started using it in a few easy
steps, see the Getting started with Execution Environments guide.
Execution Environments are meant to be a consistent, reproducible, portable, and shareable method to run Ansible
Automation jobs in the exact same way on your laptop as they are executed in Ansible AWX. This aids in the devel-
opment of automation jobs and Ansible Content that is meant to be run in Ansible AWX, or via Red Hat Ansible
Automation Platform in a predictable way.
More specifically, the term Execution Environments within the context of Ansible Runner refers to the container run-
time execution of Ansible via Ansible Runner within an OCI Compliant Container Runtime using an OCI Compliant
Container Image that appropriately bundles Ansible Base, Ansible Collection Content, and the runtime dependencies
required to support these contents. The build tooling provided by Ansible Builder aids in the creation of these images.
All aspects of running Ansible Runner in standalone mode (see: Using Runner as a standalone command line tool)
are true here with the exception that the process isolation is inherently a container runtime (podman by default).
When a job is run that uses an execution environment container image from a private/protected registry, you will first
need to authenticate to the registry.
If you are running the job manually via ansible-runner run, logging in on the command line via podman login
first is a method of authentication. Alternatively, creating a container_auth_data dictionary with the keys host,
username, and password and putting that in the job’s env/settings file is another way to ensure a successful pull of
a protected execution environment container image. Note that this involves listing sensitive information in a file which
will not automatically get cleaned up after the job run is complete.
When running a job remotely via AWX, Ansible Runner can pick up the authentication information from the Container
Registry Credential that was provided by the user. The host, username, password, and verify_ssl inputs from the
credential are passed into Ansible Runner via the container_auth_data dictionary as key word arguments into a
json file which gets deleted at the end of the job run (even if the job was cancelled/interrupted), enabling the bypassing
of sensitive information from any potentially persistent job-related files.
31
ansible-runner Documentation
There are some differences between using Ansible Runner and running Ansible directly from the command line that
have to do with configuration, content locality, and secret data.
6.2.1 Secrets
Typically with Ansible you are able to provide secret data via a series of mechanisms, many of which are pluggable
and configurable. When using Ansible Runner, however, certain considerations need to be made; these are analogous
to how Ansible AWX manage this information.
See Runner Input Directory Hierarchy for more information
Like all ansible-runner jobs, each job has an identifier associated with it which is also the name of the artifacts
subfolder where results are saved to. When a container for job isolation is launched, it will be given a name of
ansible_runner_<job identifier>. Some characters from the job identifier may be replaced with underscores
for compatibility with names that Podman and Docker allow.
This name is used internally if a command needs to be ran against the container at a later time (e.g., to stop the container
when the job is canceled).
In order to make the run container execution of Ansible easier, Ansible Runner will automatically bind mount your
local ssh agent UNIX-domain socket (SSH_AUTH_SOCK) into the container runtime. However, this does not work if
files in your ~/.ssh/ directory happen to be symlinked to another directory that is also not mounted into the container
runtime. The Ansible Runner run subcommand provides the --container-volume-mount option to address this,
among other things.
Here is an example of an ssh config file that is a symlink:
$ $ ls -l ~/.ssh/config
lrwxrwxrwx. 1 myuser myuser 34 Jul 15 19:27 /home/myuser/.ssh/config -> /home/myuser/
˓→dotfiles/ssh_config
$ ansible-runner run \
--container-volume-mount /home/myuser/dotfiles/:/home/myuser/dotfiles/ \
--process-isolation --process-isolation-executable podman \
/tmp/private --playbook my_playbook.yml -i my_inventory.ini
SEVEN
Ansible Runner supports the concept that a job run may be requested on one host but executed on another. This
capability is primarily intended to be used by Receptor.
Support for this in Runner involves a three phase process.
• Transmit: Convert the job to a binary format that can be sent to the worker node.
• Worker: Actually execute the job.
• Process: Receive job results and process them.
The following command illustrates how the three phases work together:
In this example, the ansible-runner transmit command is given a private data directory of ./demo and told to
select the test.yml playbook from it. Instead of executing the playbook as ansible-runner run would do, the data
dir and command line parameters are converted to a compressed binary stream that is emitted as stdout. The transmit
command generally takes the same command line parameters as the run command.
The ansible-runner worker command accepts this stream, runs the playbook, and generates a new compressed
binary stream of the resulting job events and artifacts. This command optionally accepts the --private-data-dir
option. If provided, it will extract the contents sent from ansible-runner transmit into that directory.
The ansible-runner process command accepts the result stream from the worker, and fires all the normal callbacks
and does job event processing. In the command above, this results in printing the playbook output and saving artifacts
to the data dir. The process command takes a data dir as a parameter, to know where to save artifacts.
A full expansion on how Receptor works is out of the scope of this document. We can set up a basic receptor node with
a simple configuration file:
---
- node:
id: primary
- log-level:
level: Debug
- local-only:
(continues on next page)
33
ansible-runner Documentation
- control-service:
service: control
filename: ./control.sock
- work-command:
worktype: ansible-runner
command: ansible-runner
params: worker
allowruntimeparams: true
Now we can repeat the transmit/worker/process example above, but instead of piping the output of transmit to
worker, we can use the receptorctl command to send it to the receptor node we just started:
The transmit and process commands do not offer any automatic deletion of the private data directory or artifacts,
because these are how the user interacts with runner.
When running ansible-runner worker, if no --private-data-dir is given, it will extract the contents to a tem-
porary directory which is deleted at the end of execution. If the --private-data-dir option is given, then the
directory will persist after the run finishes unless the --delete flag is also set. In that case, the private data directory
will be deleted before execution if it exists and also removed after execution.
The following command offers out-of-band cleanup
This would assure that old directories that fit the file glob /tmp/foo_* are deleted, which would could be used to
assure cleanup of paths created by commands like ansible-runner worker --private_data_dir=/tmp/foo_3,
for example. NOTE: see the --grace-period option, which sets the time window.
This command also takes a --remove-images option to run the podman or docker rmi command. There is otherwise
no automatic cleanup of images used by a run, even if container_auth_data is used to pull from a private container
registry. To be sure that layers are deleted as well, the --image-prune flag is necessary.
The worker command does not write artifacts, these are streamed instead, and the process command is what ulti-
mately writes the artifacts folder contents.
With the default behavior, ansible-runner process ./demo would write artifacts to ./demo/artifacts. If
you wish to better align with normal ansible-runner use, you can pass the --ident option to save to a subfolder,
so ansible-runner process ./demo --ident=43 would extract artifacts to the folder ./demo/artifacts/43.
Python code importing Ansible Runner can make use of these facilities by setting the streamer parameter to
ansible_runner.interface.run. This parameter can be set to transmit, worker or process to invoke each
of the three stages. Other parameters are as normal in the CLI.
EIGHT
DEVELOPER DOCUMENTATION
8.1.1 Subpackages
ansible_runner.config package
Submodules
ansible_runner.config.runner module
>>> rc = RunnerConfig(...)
>>> r = Runner(config=rc)
>>> r.run()
37
ansible-runner Documentation
ansible_runner.display_callback package
Submodules
ansible_runner.display_callback.callback.awx_display module
CALLBACK_TYPE = 'stdout'
CALLBACK_VERSION = 2.0
capture_event_data(event, **event_data)
clear_play()
clear_task(local=False)
set_play(play)
set_playbook(playbook)
set_task(task, local=False)
v2_on_file_diff(result)
v2_playbook_on_cleanup_task_start(task)
v2_playbook_on_handler_task_start(task)
v2_playbook_on_import_for_host(result, imported_file)
v2_playbook_on_include(included_file)
v2_playbook_on_no_hosts_matched()
v2_playbook_on_no_hosts_remaining()
v2_playbook_on_not_import_for_host(result, missing_file)
v2_playbook_on_notify(handler, host)
v2_playbook_on_play_start(play)
v2_playbook_on_setup()
v2_playbook_on_start(playbook)
v2_playbook_on_stats(stats)
v2_playbook_on_task_start(task, is_conditional)
v2_runner_item_on_failed(result)
v2_runner_item_on_ok(result)
v2_runner_item_on_skipped(result)
v2_runner_on_async_failed(result)
v2_runner_on_async_ok(result)
v2_runner_on_async_poll(result)
v2_runner_on_failed(result, ignore_errors=False)
v2_runner_on_file_diff(result, diff )
v2_runner_on_no_hosts(task)
v2_runner_on_ok(result)
v2_runner_on_skipped(result)
v2_runner_on_start(host, task)
Event used when host begins execution of a task
New in version 2.8.
v2_runner_on_unreachable(result)
v2_runner_retry(result)
class ansible_runner.display_callback.callback.awx_display.EventContext
Store global and local (per thread/process) data associated with callback events and other display output methods.
add_global(**kwargs)
add_local(**kwargs)
dump_begin(fileobj)
dump_end(fileobj)
get()
get_begin_dict()
get_end_dict()
get_global()
get_local()
remove_global(**kwargs)
remove_local(**kwargs)
set_global(**kwargs)
set_local(**kwargs)
class ansible_runner.display_callback.callback.awx_display.IsolatedFileWrite
Class that will write partial event data to a file
set(key, value)
ansible_runner.display_callback.callback.awx_display.current_time()
ansible_runner.display_callback.callback.awx_display.display_with_context(f )
ansible_runner.display_callback.callback.awx_display.with_context(**context)
ansible_runner.display_callback.callback.awx_display.with_verbosity(f )
Module contents
8.1.2 Submodules
ansible_runner.exceptions module
exception ansible_runner.exceptions.AnsibleRunnerException
Bases: Exception
Generic Runner Error
exception ansible_runner.exceptions.CallbackError
Bases: AnsibleRunnerException
Exception occurred in Callback
exception ansible_runner.exceptions.ConfigurationError
Bases: AnsibleRunnerException
Misconfiguration of Runner
ansible_runner.interface module
• process_isolation (bool) – Enable process isolation, using a container engine (e.g. pod-
man).
• process_isolation_executable (str) – Process isolation executable or container en-
gine used to isolate execution. (default: podman)
• container_image (str) – Container image to use when running an ansible task
• container_volume_mounts (list) – List of bind mounts in the form
‘host_dir:/container_dir:labels. (default: None)
• container_options (list) – List of container options to pass to execution engine.
• container_workdir (str) – The working directory within the container.
• fact_cache (str) – A string that will be used as the name for the subdirectory of the fact
cache in artifacts directory. This is only used for ‘jsonfile’ type fact caches.
• fact_cache_type (str) – A string of the type of fact cache to use. Defaults to ‘jsonfile’.
• 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.
• event_handler (Callable) – An optional callback that will be invoked any time an event
is received by Runner itself, return True to keep the event
• cancel_callback (Callable) – An optional callback that can inform runner to cancel
(returning True) or not (returning False)
• finished_callback (Callable) – An optional callback that will be invoked at shutdown
after process cleanup.
• status_handler (Callable) – An optional callback that will be invoked any time the
status changes (e.g. . . started, running, failed, successful, timeout)
• artifacts_handler (Callable) – An optional callback that will be invoked at the end of
the run to deal with the artifacts from the run.
• check_job_event_data (bool) – Check if job events data is completely generated. If
event data is not completely generated and if value is set to ‘True’ it will raise ‘AnsibleRun-
nerException’ exception, if set to ‘False’ it log a debug message and continue execution.
Default value is ‘False’
Returns
Returns a tuple of response and error string. In case if runner_mode is set to pexpect the error
value is empty as pexpect uses same output descriptor for stdout and stderr.
ansible_runner.interface.get_inventory(action, inventories, response_format=None, host=None,
playbook_dir=None, vault_ids=None, vault_password_file=None,
output_file=None, export=None, **kwargs)
Run an ansible-inventory command to get inventory related details.
Parameters
• action (str) – Valid values are one of graph, host, list. graph returns the inventory
graph. host returns info for a specific host and works as an inventory script. list returns
info for all hosts and also works as an inventory script.
• inventories (list) – List of inventory host path.
• response_format (str) – The output format for response. Valid values can be one of
json, yaml, toml. Default is json. If action is graph only allowed value is json.
• host (str) – When action is set to host this parameter is used to get the host specific
information.
• playbook_dir (str) – This parameter is used to sets the relative path for the inventory.
• vault_ids (str) – The vault identity to use.
• vault_password_file (str) – The vault password files to use.
• output_file (str) – The file path in which inventory details should be sent to.
• export (bool) – The boolean value if set represent in a way that is optimized for export,not
as an accurate representation of how Ansible has processed it.
• runner_mode (str) – The applicable values are pexpect and subprocess. Default is set
to subprocess.
• host_cwd (str) – The host current working directory to be mounted within the container
(if enabled) and will be the work directory within container.
• envvars (dict) – Environment variables to be used when running Ansible. Environment
variables will also be read from env/envvars in private_data_dir
• passwords (dict) – A dictionary containing password prompt patterns and response val-
ues 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 run-
time 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.
• quiet (bool) – Disable all output
• json_mode (bool) – Store event data in place of stdout on the console and in the stdout file
• artifact_dir (str) – The path to the directory where artifacts should live, this defaults to
‘artifacts’ under the private data dir
• project_dir (str) – The path to the playbook content, this defaults to ‘project’ within the
private data dir
• rotate_artifacts (int) – Keep at most n artifact directories, disable with a value of 0
which is the default
• timeout (int) – The timeout value in seconds that will be passed to either pexpect of
subprocess invocation (based on runner_mode selected) while executing command. It
the timeout is triggered it will force cancel the execution.
• process_isolation (bool) – Enable process isolation, using a container engine (e.g. pod-
man).
• process_isolation_executable (str) – Process isolation executable or container en-
gine used to isolate execution. (default: podman)
• container_image (str) – Container image to use when running an ansible task
• container_volume_mounts (list) – List of bind mounts in the form
‘host_dir:/container_dir:labels. (default: None)
• container_options (list) – List of container options to pass to execution engine.
• runner_mode (str) – The applicable values are pexpect and subprocess. Default is set
to subprocess.
• host_cwd (str) – The host current working directory to be mounted within the container
(if enabled) and will be the work directory within container.
• envvars (dict) – Environment variables to be used when running Ansible. Environment
variables will also be read from env/envvars in private_data_dir
• passwords (dict) – A dictionary containing password prompt patterns and response val-
ues 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 run-
time 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.
• quiet (bool) – Disable all output
• json_mode (bool) – Store event data in place of stdout on the console and in the stdout file
• artifact_dir (str) – The path to the directory where artifacts should live, this defaults to
‘artifacts’ under the private data dir
• project_dir (str) – The path to the playbook content, this defaults to ‘project’ within the
private data dir
• rotate_artifacts (int) – Keep at most n artifact directories, disable with a value of 0
which is the default
• timeout (int) – The timeout value in seconds that will be passed to either pexpect of
subprocess invocation (based on runner_mode selected) while executing command. It
the timeout is triggered it will force cancel the execution.
• process_isolation (bool) – Enable process isolation, using a container engine (e.g. pod-
man).
• process_isolation_executable (str) – Process isolation executable or container en-
gine used to isolate execution. (default: podman)
• container_image (str) – Container image to use when running an ansible task
• container_volume_mounts (list) – List of bind mounts in the form
‘host_dir:/container_dir:labels. (default: None)
• container_options (list) – List of container options to pass to execution engine.
• container_workdir (str) – The working directory within the container.
• fact_cache (str) – A string that will be used as the name for the subdirectory of the fact
cache in artifacts directory. This is only used for ‘jsonfile’ type fact caches.
• fact_cache_type (str) – A string of the type of fact cache to use. Defaults to ‘jsonfile’.
• 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.
• event_handler (Callable) – An optional callback that will be invoked any time an event
is received by Runner itself, return True to keep the event
• host_cwd (str) – The host current working directory to be mounted within the container
(if enabled) and will be the work directory within container.
• envvars (dict) – Environment variables to be used when running Ansible. Environment
variables will also be read from env/envvars in private_data_dir
• passwords (dict) – A dictionary containing password prompt patterns and response val-
ues 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 run-
time 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.
• quiet (bool) – Disable all output
• json_mode (bool) – Store event data in place of stdout on the console and in the stdout file
• artifact_dir (str) – The path to the directory where artifacts should live, this defaults to
‘artifacts’ under the private data dir
• project_dir (str) – The path to the playbook content, this defaults to ‘project’ within the
private data dir
• rotate_artifacts (int) – Keep at most n artifact directories, disable with a value of 0
which is the default
• timeout (int) – The timeout value in seconds that will be passed to either pexpect of
subprocess invocation (based on runner_mode selected) while executing command. It
the timeout is triggered it will force cancel the execution.
• process_isolation (bool) – Enable process isolation, using a container engine (e.g. pod-
man).
• process_isolation_executable (str) – Process isolation executable or container en-
gine used to isolate execution. (default: podman)
• container_image (str) – Container image to use when running an ansible task
• container_volume_mounts (list) – List of bind mounts in the form
‘host_dir:/container_dir:labels. (default: None)
• container_options (list) – List of container options to pass to execution engine.
• container_workdir (str) – The working directory within the container.
• fact_cache (str) – A string that will be used as the name for the subdirectory of the fact
cache in artifacts directory. This is only used for ‘jsonfile’ type fact caches.
• fact_cache_type (str) – A string of the type of fact cache to use. Defaults to ‘jsonfile’.
• 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.
• event_handler (Callable) – An optional callback that will be invoked any time an event
is received by Runner itself, return True to keep the event
• cancel_callback (Callable) – An optional callback that can inform runner to cancel
(returning True) or not (returning False)
Parameters
• role (str) – Simple role name, or fully qualified collection role name, to query.
• collection (str) – If specified, will be combined with the role name to form a fully qual-
ified collection role name. If this is supplied, the role param should not be fully qualified.
• playbook_dir (str) – This parameter is used to set the relative path to handle playbook
adjacent installed roles.
• runner_mode (str) – The applicable values are pexpect and subprocess. Default is set
to subprocess.
• host_cwd (str) – The host current working directory to be mounted within the container
(if enabled) and will be the work directory within container.
• envvars (dict) – Environment variables to be used when running Ansible. Environment
variables will also be read from env/envvars in private_data_dir
• passwords (dict) – A dictionary containing password prompt patterns and response val-
ues 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 run-
time 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.
• quiet (bool) – Disable all output
• json_mode (bool) – Store event data in place of stdout on the console and in the stdout file
• artifact_dir (str) – The path to the directory where artifacts should live, this defaults to
‘artifacts’ under the private data dir
• project_dir (str) – The path to the playbook content, this defaults to ‘project’ within the
private data dir
• rotate_artifacts (int) – Keep at most n artifact directories, disable with a value of 0
which is the default
• timeout (int) – The timeout value in seconds that will be passed to either pexpect of
subprocess invocation (based on runner_mode selected) while executing command. If
the timeout is triggered, it will force cancel the execution.
• process_isolation (bool) – Enable process isolation using a container engine, such as
podman.
• process_isolation_executable (str) – Process isolation executable or container en-
gine used to isolate execution. (default: podman)
• container_image (str) – Container image to use when running an Ansible task
• container_volume_mounts (list) – List of bind mounts in the form host_dir:/
container_dir:labels. (default: None)
• container_options (list) – List of container options to pass to execution engine.
• container_workdir (str) – The working directory within the container.
• fact_cache (str) – A string that will be used as the name for the subdirectory of the fact
cache in artifacts directory. This is only used for ‘jsonfile’ type fact caches.
• fact_cache_type (str) – A string of the type of fact cache to use. Defaults to ‘jsonfile’.
• 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.
• event_handler (Callable) – An optional callback that will be invoked any time an event
is received by Runner itself, return True to keep the event
• cancel_callback (Callable) – An optional callback that can inform runner to cancel
(returning True) or not (returning False)
• finished_callback (Callable) – An optional callback that will be invoked at shutdown
after process cleanup.
• status_handler (Callable) – An optional callback that will be invoked any time the
status changes (for example: started, running, failed, successful, timeout)
• artifacts_handler (Callable) – An optional callback that will be invoked at the end of
the run to deal with the artifacts from the run.
• check_job_event_data (bool) – Check if job events data is completely generated. If event
data is not completely generated and if value is set to ‘True’ it will raise ‘AnsibleRunnerEx-
ception’ exception. If set to ‘False’, log a debug message and continue execution. Default
value is ‘False’
Returns
A tuple of response and error string. The response is a dictionary object (as returned by ansible-
doc JSON output) containing each role found, or an empty dict if none are found.
Parameters
• collection (str) – A fully qualified collection name used to filter the results.
• playbook_dir (str) – This parameter is used to set the relative path to handle playbook
adjacent installed roles.
• runner_mode (str) – The applicable values are pexpect and subprocess. Default is set
to subprocess.
• host_cwd (str) – The host current working directory to be mounted within the container
(if enabled) and will be the work directory within container.
• envvars (dict) – Environment variables to be used when running Ansible. Environment
variables will also be read from env/envvars in private_data_dir
• passwords (dict) – A dictionary containing password prompt patterns and response val-
ues 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 run-
time 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.
• quiet (bool) – Disable all output
• json_mode (bool) – Store event data in place of stdout on the console and in the stdout file
• artifact_dir (str) – The path to the directory where artifacts should live, this defaults to
‘artifacts’ under the private data dir
• project_dir (str) – The path to the playbook content, this defaults to ‘project’ within the
private data dir
• rotate_artifacts (int) – Keep at most n artifact directories, disable with a value of 0
which is the default
• timeout (int) – The timeout value in seconds that will be passed to either pexpect of
subprocess invocation (based on runner_mode selected) while executing command. If
the timeout is triggered, it will force cancel the execution.
• process_isolation (bool) – Enable process isolation using a container engine, such as
podman.
• process_isolation_executable (str) – Process isolation executable or container en-
gine used to isolate execution. (default: podman)
• container_image (str) – Container image to use when running an Ansible task
• container_volume_mounts (list) – List of bind mounts in the form host_dir:/
container_dir:labels. (default: None)
• container_options (list) – List of container options to pass to execution engine.
• container_workdir (str) – The working directory within the container.
• fact_cache (str) – A string that will be used as the name for the subdirectory of the fact
cache in artifacts directory. This is only used for ‘jsonfile’ type fact caches.
• fact_cache_type (str) – A string of the type of fact cache to use. Defaults to ‘jsonfile’.
• 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.
• event_handler (Callable) – An optional callback that will be invoked any time an event
is received by Runner itself, return True to keep the event
• cancel_callback (Callable) – An optional callback that can inform runner to cancel
(returning True) or not (returning False)
• finished_callback (Callable) – An optional callback that will be invoked at shutdown
after process cleanup.
• status_handler (Callable) – An optional callback that will be invoked any time the
status changes (for example: started, running, failed, successful, timeout)
• artifacts_handler (Callable) – An optional callback that will be invoked at the end of
the run to deal with the artifacts from the run.
• check_job_event_data (bool) – Check if job events data is completely generated. If event
data is not completely generated and if value is set to ‘True’ it will raise ‘AnsibleRunnerEx-
ception’ exception. If set to ‘False’, log a debug message and continue execution. Default
value is ‘False’
Returns
A tuple of response and error string. The response is a dictionary object (as returned by ansible-
doc JSON output) containing each role found, or an empty dict if none are found.
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 list) – The playbook (either a list or dictionary of plays, or as a path
relative to private_data_dir/project) that will be invoked by runner when executing
Ansible.
• module (str) – The module that will be invoked in ad-hoc mode by runner when executing
Ansible.
• module_args (str) – The module arguments that will be supplied to ad-hoc mode.
• host_pattern (str) – The host pattern to match when running in ad-hoc mode.
• inventory (str or dict or list) – Overrides 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/inventory directory or an absolute
path to the inventory file
– Native python dict supporting the YAML/json inventory structure
– A text INI formatted string
– A list of inventory sources, or an empty list to disable passing inventory
• role (str) – Name of the role to execute.
• roles_path (dict or list) – Directory or list of directories to assign to ANSI-
BLE_ROLES_PATH
• 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 val-
ues 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 run-
time 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) – Command line options passed to Ansible read from env/cmdline in
private_data_dir
• suppress_env_files (bool) – Disable the writing of files into the env which may store
sensitive information
• limit (str) – Matches ansible’s --limit parameter to further constrain the inventory to
be used
• forks (int) – Control Ansible parallel concurrency
• settings (dict) – A dictionary containing settings values for the ansible-runner run-
time 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.
• quiet (bool) – Disable all output
• json_mode (bool) – Store event data in place of stdout on the console and in the stdout file
• artifact_dir (str) – The path to the directory where artifacts should live, this defaults to
‘artifacts’ under the private data dir
• project_dir (str) – The path to the playbook content, this defaults to ‘project’ within the
private data dir
• rotate_artifacts (int) – Keep at most n artifact directories, disable with a value of 0
which is the default
• timeout (int) – The timeout value in seconds that will be passed to either pexpect of
subprocess invocation (based on runner_mode selected) while executing command. It
the timeout is triggered it will force cancel the execution.
• process_isolation (bool) – Enable process isolation, using a container engine (e.g. pod-
man).
• process_isolation_executable (str) – Process isolation executable or container en-
gine used to isolate execution. (default: podman)
• container_image (str) – Container image to use when running an ansible task
• container_volume_mounts (list) – List of bind mounts in the form
‘host_dir:/container_dir:labels. (default: None)
• container_options (list) – List of container options to pass to execution engine.
• container_workdir (str) – The working directory within the container.
• fact_cache (str) – A string that will be used as the name for the subdirectory of the fact
cache in artifacts directory. This is only used for ‘jsonfile’ type fact caches.
• fact_cache_type (str) – A string of the type of fact cache to use. Defaults to ‘jsonfile’.
• 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.
• event_handler (Callable) – An optional callback that will be invoked any time an event
is received by Runner itself, return True to keep the event
• cancel_callback (Callable) – An optional callback that can inform runner to cancel
(returning True) or not (returning False)
• finished_callback (Callable) – An optional callback that will be invoked at shutdown
after process cleanup.
• status_handler (Callable) – An optional callback that will be invoked any time the
status changes (e.g. . . started, running, failed, successful, timeout)
• artifacts_handler (Callable) – An optional callback that will be invoked at the end of
the run to deal with the artifacts from the run.
ansible_runner.loader module
• objtype (Any) – The object type of the file contents. This is used to type check the dese-
rialized content against the contents loaded from disk. Ignore serializing if objtype is str.
Only Mapping or str types are supported.
• encoding (str) – The file contents text encoding.
Returns
The deserialized file contents which could be either a string object or a dict object
Raises
ConfigurationError on error during file load or deserialization.
ansible_runner.runner module
{
"event": "runner_on_ok",
"uuid": "00a50d9c-161a-4b74-b978-9f60becaf209",
"stdout": "ok: [localhost] => {\r\n \" msg\":\"Test!\"\r\n}",
"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",
(continues on next page)
get_fact_cache(host)
Get the entire fact cache only if the fact_cache_type is ‘jsonfile’
classmethod handle_termination(pid, pidfile=None)
Internal method to terminate a subprocess spawned by pexpect representing an invocation of runner.
Parameters
• pid – the process id of the running the job.
• pidfile – the daemon’s PID file
host_events(host)
Given a host name, this will return all task events executed on that host
kill_container()
Internal method to terminate a container being used for job isolation
run()
Launch the Ansible task configured in self.config (A RunnerConfig object), returns once the invocation is
complete
set_fact_cache(host, data)
Set the entire fact cache data only if the fact_cache_type is ‘jsonfile’
property stats
Returns the final high level stats from the Ansible run
Example:
{‘dark’: {}, ‘failures’: {}, ‘skipped’: {}, ‘ok’: {u’localhost’: 2}, ‘processed’: {u’localhost’: 1}}
status_callback(status)
property stderr
Returns an open file handle to the stderr representing the Ansible run
property stdout
Returns an open file handle to the stdout representing the Ansible run
ansible_runner.runner_config module
ansible_runner.utils module
class ansible_runner.utils.Bunch(**kwargs)
Bases: object
Collect a bunch of variables together in an object. This is a slight modification of Alex Martelli’s and Doug
Hudgeon’s Bunch pattern.
get(key)
update(**kwargs)
close() → None
flush() → None
ansible_runner.utils.args2cmdline(*args)
ansible_runner.utils.get_plugin_dir() → str
NINE
• genindex
• modindex
• search
61
ansible-runner Documentation
a
ansible_runner.display_callback, 40
ansible_runner.display_callback.callback.awx_display,
38
ansible_runner.exceptions, 40
ansible_runner.interface, 41
ansible_runner.loader, 56
ansible_runner.runner, 57
ansible_runner.runner_config, 58
ansible_runner.utils, 58
63
ansible-runner Documentation
65
ansible-runner Documentation
event_callback() (ansible_runner.runner.Runner H
method), 57 handle_termination() (ansi-
EVENT_DATA_RE (ansible_runner.utils.OutputEventFilter ble_runner.runner.Runner class method),
attribute), 59 58
EventContext (class in ansi- host_events() (ansible_runner.runner.Runner
ble_runner.display_callback.callback.awx_display), method), 58
39
events (ansible_runner.runner.Runner property), 57 I
EVENTS_WITHOUT_PLAY (ansi-
init_command_config() (in module ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
ble_runner.interface), 51
attribute), 38
init_plugin_docs_config() (in module ansi-
EVENTS_WITHOUT_TASK (ansi-
ble_runner.interface), 51
ble_runner.display_callback.callback.awx_display.CallbackModule
init_runner() (in module ansible_runner.interface),
attribute), 38
51
is_dir_owner() (in module ansible_runner.utils), 60
F isfile() (ansible_runner.loader.ArtifactLoader
flush() (ansible_runner.utils.OutputEventFilter method), 56
method), 59 isinventory() (in module ansible_runner.utils), 60
IsolatedFileWrite (class in ansi-
G ble_runner.display_callback.callback.awx_display),
get() (ansible_runner.display_callback.callback.awx_display.EventContext
40
method), 40 isplaybook() (in module ansible_runner.utils), 60
get() (ansible_runner.utils.Bunch method), 58
get_ansible_config() (in module ansi- K
ble_runner.interface), 41 kill_container() (ansible_runner.runner.Runner
get_begin_dict() (ansi- method), 58
ble_runner.display_callback.callback.awx_display.EventContext
method), 40 L
get_callback_dir() (in module ansible_runner.utils),
load_file() (ansible_runner.loader.ArtifactLoader
60
method), 56
get_end_dict() (ansi-
ble_runner.display_callback.callback.awx_display.EventContext
method), 40
M
get_executable_path() (in module ansi- module
ble_runner.utils), 60 ansible_runner.display_callback, 40
get_fact_cache() (ansible_runner.runner.Runner ansible_runner.display_callback.callback.awx_display,
method), 58 38
ansible_runner.exceptions,
get_global() (ansible_runner.display_callback.callback.awx_display.EventContext 40
method), 40 ansible_runner.interface, 41
get_inventory() (in module ansible_runner.interface), ansible_runner.loader, 56
42 ansible_runner.runner, 57
ansible_runner.runner_config, 58
get_local() (ansible_runner.display_callback.callback.awx_display.EventContext
method), 40 ansible_runner.utils, 58
get_plugin_dir() (in module ansible_runner.utils), 60
get_plugin_docs() (in module ansi- O
ble_runner.interface), 44 open_fifo_write() (in module ansible_runner.utils),
get_plugin_docs_async() (in module ansi- 60
ble_runner.interface), 46 OutputEventFilter (class in ansible_runner.utils), 59
get_plugin_list() (in module ansi-
ble_runner.interface), 46 R
get_role_argspec() (in module ansi- register_for_cleanup() (in module ansi-
ble_runner.interface), 48 ble_runner.utils), 60
get_role_list() (in module ansible_runner.interface),
49
66 Index
ansible-runner Documentation
Index 67
ansible-runner Documentation
v2_runner_on_async_poll() (ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
method), 39
v2_runner_on_failed() (ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
method), 39
v2_runner_on_file_diff() (ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
method), 39
v2_runner_on_no_hosts() (ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
method), 39
v2_runner_on_ok() (ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
method), 39
v2_runner_on_skipped() (ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
method), 39
v2_runner_on_start() (ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
method), 39
v2_runner_on_unreachable() (ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
method), 39
v2_runner_retry() (ansi-
ble_runner.display_callback.callback.awx_display.CallbackModule
method), 39
W
with_context() (in module ansi-
ble_runner.display_callback.callback.awx_display),
40
with_verbosity() (in module ansi-
ble_runner.display_callback.callback.awx_display),
40
write() (ansible_runner.utils.OutputEventFilter
method), 59
68 Index