ansible_runner package

Subpackages

Submodules

ansible_runner.exceptions module

exception ansible_runner.exceptions.AnsibleRunnerException[source]

Bases: Exception

Generic Runner Error

exception ansible_runner.exceptions.CallbackError[source]

Bases: AnsibleRunnerException

Exception occurred in Callback

exception ansible_runner.exceptions.ConfigurationError[source]

Bases: AnsibleRunnerException

Misconfiguration of Runner

ansible_runner.interface module

ansible_runner.interface.get_ansible_config(action, config_file=None, only_changed=None, **kwargs)[source]

Run an ansible-config command to get ansible configuration releated details.

Parameters:
  • action (str) – Valid values are one of list, dump, view list returns all config options, dump returns the active configuration and view returns the view of configuration file.

  • config_file (str) – Path to configuration file, defaults to first file found in precedence. .

  • only_changed (bool) – The boolean value when set to True returns only the configurations that have changed from the default. This parameter is applicable only when action is set to dump.

  • runner_mode (str) – The applicable values are pexpect and subprocess. Default is set to subprocess.

  • host_cwd (str) – The current working directory from which the command in executable_cmd should be be executed.

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

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

  • process_isolation_executable (str) – Process isolation executable or container engine 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 ‘AnsibleRunnerException’ 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)[source]

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

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

  • process_isolation_executable (str) – Process isolation executable or container engine 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 ‘AnsibleRunnerException’ 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. If the vaue of response_format is json it returns a python dictionary object.

ansible_runner.interface.get_plugin_docs(plugin_names, plugin_type=None, response_format=None, snippet=False, playbook_dir=None, module_path=None, **kwargs)[source]

Run an ansible-doc command to get plugin docs in the foreground and return a Runner object when complete.

Parameters:
  • plugin_names (list) – The name of the plugins to get docs.

  • plugin_type (str) – The type of the plugin mentioned in plugins_names. Valid values are become, cache, callback, cliconf, connection, httpapi, inventory, lookup, netconf, shell, vars, module, strategy. If the value is not provided it defaults to module.

  • response_format (str) – The output format for response. Valid values can be one of json or human and the response is either json string or plain text in human readable foramt. Default value is json.

  • snippet (bool) – Show playbook snippet for specified plugin(s).

  • playbook_dir (str) – This parameter is used to sets the relative path to handle playbook adjacent installed plugins.

  • module_path (str) – This parameter is prepend colon-separated path(s) to module library (default=~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules).

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

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

  • process_isolation_executable (str) – Process isolation executable or container engine 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 ‘AnsibleRunnerException’ 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. If the value of response_format is json it returns a python dictionary object.

ansible_runner.interface.get_plugin_docs_async(plugin_names, plugin_type=None, response_format=None, snippet=False, playbook_dir=None, module_path=None, **kwargs)[source]

Run an ansible-doc command in the background which will start immediately. Returns the thread object and a Runner object.

This uses the same parameters as ansible_runner.interface.get_plugin_docs()

Returns:

A tuple containing a threading.Thread object and a ansible_runner.runner.Runner object

ansible_runner.interface.get_plugin_list(list_files=None, response_format=None, plugin_type=None, playbook_dir=None, module_path=None, **kwargs)[source]

Run an ansible-doc command to get list of installed Ansible plugins.

Parameters:
  • list_files (bool) – The boolean parameter is set to True returns file path of the plugin along with the plugin name.

  • response_format (str) – The output format for response. Valid values can be one of json or human and the response is either json string or plain text in human readable foramt. Default value is json.

  • plugin_type (str) – The type of the plugin mentioned in plugins_names. Valid values are become, cache, callback, cliconf, connection, httpapi, inventory, lookup, netconf, shell, vars, module, strategy. If the value is not provided it defaults to module.

  • playbook_dir (str) – This parameter is used to sets the relative path to handle playbook adjacent installed plugins.

  • module_path (str) – This parameter is prepend colon-separated path(s) to module library (default=~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules).

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

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

  • process_isolation_executable (str) – Process isolation executable or container engine 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 ‘AnsibleRunnerException’ 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. If the value of response_format is json it returns a python dictionary object.

ansible_runner.interface.get_role_argspec(role, collection=None, playbook_dir=None, **kwargs)[source]

Run an ansible-doc command to get a role argument specification.

Note

Version added: 2.2

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

  • 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 engine 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 ‘AnsibleRunnerException’ 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.

ansible_runner.interface.get_role_list(collection=None, playbook_dir=None, **kwargs)[source]

Run an ansible-doc command to get list of installed collection roles.

Only roles that have an argument specification defined are returned.

Note

Version added: 2.2

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

  • 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 engine 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 ‘AnsibleRunnerException’ 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.

ansible_runner.interface.init_command_config(executable_cmd, cmdline_args=None, **kwargs)[source]

Initialize the Runner() instance

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

See parameters given to ansible_runner.interface.run_command()

ansible_runner.interface.init_plugin_docs_config(plugin_names, plugin_type=None, response_format=None, snippet=False, playbook_dir=None, module_path=None, **kwargs)[source]

Initialize the Runner() instance

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

See parameters given to ansible_runner.interface.get_plugin_docs()

ansible_runner.interface.init_runner(**kwargs)[source]

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)[source]

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 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 (str or list) – Directory or list of directories to assign to ANSIBLE_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 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) – 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

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

  • streamer (str) – Optionally invoke ansible-runner as one of the steps in the streaming pipeline

  • _input (io.FileIO) – An optional file or file-like object for use as input in a streaming pipeline

  • _output (io.FileIO) – An optional file or file-like object for use as output in a streaming pipeline

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

  • process_isolation (bool) – Enable process isolation, using either a container engine (e.g. podman) or a sandbox (e.g. bwrap).

  • process_isolation_executable (str) – Process isolation executable or container engine used to isolate execution. (default: podman)

  • process_isolation_path (str) – Path that an isolated playbook run will use for staging. (default: /tmp)

  • process_isolation_hide_paths (str or list) – A path or list of paths on the system that should be hidden from the playbook run.

  • process_isolation_show_paths (str or list) – A path or list of paths on the system that should be exposed to the playbook run.

  • process_isolation_ro_paths (str or list) – A path or list of paths on the system that should be exposed to the playbook run as read-only.

  • 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. (default: None)

  • container_options (list) – List of container options to pass to execution engine.

  • directory_isolation_base_path (str) – An optional path will be used as the base path to create a temp directory, the project contents will be copied to this location which will then be used as the working directory during playbook execution.

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

  • omit_event_data (bool) – Omits extra ansible event data from event payload (stdout and event still included)

  • only_failed_event_data (bool) – Omits extra ansible event data unless it’s a failed event (stdout and event still included)

  • 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 ‘AnsibleRunnerException’ exception, if set to ‘False’ it log a debug message and continue execution. Default value is ‘False’

Returns:

A ansible_runner.runner.Runner object, or a simple object containing rc if run remotely

ansible_runner.interface.run_async(**kwargs)[source]

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.interface.run_command(executable_cmd, cmdline_args=None, **kwargs)[source]

Run an (Ansible) commands in the foreground and return a Runner object when complete.

Parameters:
  • executable_cmd (str) – The command to be executed.

  • cmdline_args (list) – A list of arguments to be passed to the executable command.

  • input_fd (int) – This parameter is applicable when runner_mode is set to subprocess, it provides the input file descrption to interact with the sub-process running the command.

  • output_fd (int) – The output file descriptor to stream the output of command execution.

  • error_fd (int) – This parameter is applicable when runner_mode is set to subprocess, it provides the error file descrption to read the error received while executing the command.

  • runner_mode (str) – The applicable values are pexpect and subprocess. If the value of input_fd parameter is set or the executable command is one of ansible-config, ansible-doc or ansible-galaxy the default value is set to subprocess else in other cases it is set to pexpect.

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

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

  • process_isolation_executable (str) – Process isolation executable or container engine 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 ‘AnsibleRunnerException’ exception, if set to ‘False’ it log a debug message and continue execution. Default value is ‘False’

Returns:

Returns a tuple of response, error string and return code. 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.run_command_async(executable_cmd, cmdline_args=None, **kwargs)[source]

Run an (Ansible) commands 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_command()

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: str)[source]

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: str) str[source]

Transform the path to an absolute path

Parameters:

path (str) – The path to transform to an absolute path

Returns:

The absolute path to the file.

isfile(path: str) bool[source]

Check if the path is a file

Parameters:

path (str) – The path to the file to check. If the path is relative it will be exanded to an absolute path

Returns:

True if path is a file, False otherwise.

load_file(path: str, objtype: Any | None = None, encoding='utf-8') bytes | str | dict | None[source]

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

Parameters:
  • path (str) – The full or relative path to the file to be loaded.

  • objtype (Any) – 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 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

class ansible_runner.runner.Runner(config, cancel_callback=None, remove_partials=True, event_handler=None, artifacts_handler=None, finished_callback=None, status_handler=None)[source]

Bases: object

event_callback(event_data)[source]

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

property 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] => {\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",
       "host": "localhost",
       "task_path": "/tmp/demo/project/test.yml:3"
    }
}
get_fact_cache(host)[source]

Get the entire fact cache only if the fact_cache_type is ‘jsonfile’

classmethod handle_termination(pid, pidfile=None)[source]

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)[source]

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

kill_container()[source]

Internal method to terminate a container being used for job isolation

run()[source]

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

set_fact_cache(host, data)[source]

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)[source]
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)[source]

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)[source]
update(**kwargs)[source]
class ansible_runner.utils.OutputEventFilter(handle: StreamReaderWriter, event_callback: Callable[[dict], None], suppress_ansible_output: bool = False, output_json: bool = False)[source]

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() None[source]
flush() None[source]
write(data: str) None[source]
ansible_runner.utils.args2cmdline(*args)[source]
ansible_runner.utils.check_isolation_executable_installed(isolation_executable: str) bool[source]

Check that process isolation executable is installed.

Parameters:

isolation_executable (str) – Executable name (e.g. podman, docker, bwrap).

Returns:

True if the executable is installed, False otherwise.

ansible_runner.utils.cleanup_artifact_dir(path: str, num_keep: int = 0) None[source]
ansible_runner.utils.cleanup_folder(folder: str) bool[source]

Deletes folder, returns True or False based on whether a change happened.

ansible_runner.utils.cli_mounts()[source]
ansible_runner.utils.collect_new_events(event_path: str, old_events: dict) Iterator[tuple[dict, dict]][source]

Collect new events for the ‘events’ generator property

ansible_runner.utils.dump_artifact(obj: str, path: str, filename: str | None = None) str[source]

Write the artifact to disk at the specified path

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

  • path (str) – The full path to the artifacts data directory.

  • filename (str) – The name of file to write the artifact to. If the filename is not provided, then one will be generated.

Returns:

The full path filename for the artifact that was generated.

ansible_runner.utils.dump_artifacts(kwargs: dict) None[source]

Introspect the kwargs and dump objects to disk

ansible_runner.utils.ensure_str(s: Any, encoding='utf-8', errors='strict') str[source]

Coerce s to str.

  • str -> str

  • bytes -> decoded to str

ansible_runner.utils.get_callback_dir() str[source]
ansible_runner.utils.get_executable_path(name: str) str[source]
ansible_runner.utils.get_plugin_dir() str[source]
ansible_runner.utils.is_dir_owner(directory: str) bool[source]

Returns True if current user is the owner of directory

ansible_runner.utils.isinventory(obj: Any) bool[source]

Inspects the object and returns if it is an inventory

Parameters:

obj (Any) – The object to be inspected by this function.

Returns:

True if the object is an inventory dict and False if it is not.

ansible_runner.utils.isplaybook(obj: Any) bool[source]

Inspects the object and returns if it is a playbook

Parameters:

obj (Any) – The object to be inspected by this function.

Returns:

True if the object is a list and False if it is not.

ansible_runner.utils.open_fifo_write(path: str, data: str | bytes) None[source]

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.

ansible_runner.utils.register_for_cleanup(folder: str) None[source]

Provide the path to a folder to make sure it is deleted when execution finishes. The folder need not exist at the time when this is called.

ansible_runner.utils.sanitize_container_name(original_name: str) str[source]

Docker and podman will only accept certain characters in container names This takes a given name from user-specified values and replaces the invalid characters so it can be used in docker/podman CLI commands

Parameters:

original_name (str) – Container name containing potentially invalid characters

ansible_runner.utils.sanitize_json_response(data: str) str[source]

Removes warning message from response message emitted by Ansible command line utilities.

Parameters:

data (str) – The string data to be sanitized

ansible_runner.utils.signal_handler() Callable[[], bool] | None[source]