Python API

There are several interesting ways to use Ansible from an API perspective. You can use the Ansible python API to control nodes, you can extend Ansible to respond to various python events, you can write various plugins, and you can plug in inventory data from external data sources. This document covers the Runner and Playbook API at a basic level.

If you are looking to use Ansible programmatically from something other than Python, trigger events asynchronously, or have access control and logging demands, take a look at Ansible Tower as it has a very nice REST API that provides all of these things at a higher level.

Ansible is written in its own API so you have a considerable amount of power across the board. This chapter discusses the Python API.

The Python API is very powerful, and is how the ansible CLI and ansible-playbook are implemented. In version 2.0 the core ansible got rewritten and the API was mostly rewritten.

Python API 2.0

In 2.0 things get a bit more complicated to start, but you end up with much more discrete and readable classes:


from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from import Play
from ansible.executor.task_queue_manager import TaskQueueManager

Options = namedtuple('Options', ['connection','module_path', 'forks', 'remote_user', 'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])
# initialize needed objects
variable_manager = VariableManager()
loader = DataLoader()
options = Options(connection='local', module_path='/path/to/mymodules', forks=100, remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None, become_user=None, verbosity=None, check=False)
passwords = dict(vault_pass='secret')

# create inventory and pass to var manager
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list='localhost')

# create play with tasks
play_source =  dict(
        name = "Ansible Play",
        hosts = 'localhost',
        gather_facts = 'no',
        tasks = [ dict(action=dict(module='debug', args=(msg='Hello Galaxy!'))) ]
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

# actually run it
tqm = None
    tqm = TaskQueueManager(
    result =
    if tqm is not None:

Python API pre 2.0

It’s pretty simple:

import ansible.runner

runner = ansible.runner.Runner(
datastructure =

The run method returns results per host, grouped by whether they could be contacted or not. Return types are module specific, as expressed in the About Modules documentation.:

    "dark" : {
       "" : "failure message"
    "contacted" : {
       "" : 1

A module can return any type of JSON data it wants, so Ansible can be used as a framework to rapidly build powerful applications and scripts.

Detailed API Example

The following script prints out the uptime information for all hosts:


import ansible.runner
import sys

# construct the ansible runner and execute on all hosts
results = ansible.runner.Runner(
    pattern='*', forks=10,
    module_name='command', module_args='/usr/bin/uptime',

if results is None:
   print "No hosts found"

print "UP ***********"
for (hostname, result) in results['contacted'].items():
    if not 'failed' in result:
        print "%s >>> %s" % (hostname, result['stdout'])

print "FAILED *******"
for (hostname, result) in results['contacted'].items():
    if 'failed' in result:
        print "%s >>> %s" % (hostname, result['msg'])

print "DOWN *********"
for (hostname, result) in results['dark'].items():
    print "%s >>> %s" % (hostname, result)

Advanced programmers may also wish to read the source to ansible itself, for it uses the API (with all available options) to implement the ansible command line tools (lib/ansible/cli/).


Developing Dynamic Inventory Sources
Developing dynamic inventory integrations
Developing Modules
How to develop modules
Developing Plugins
How to develop plugins
Development Mailing List
Mailing list for development topics
#ansible IRC chat channel