ansible/docsite/rst/developing_api.rst

163 lines
5.4 KiB
ReStructuredText
Raw Normal View History

2013-09-30 01:10:28 +02:00
Python API
==========
.. contents:: Topics
2012-08-31 05:55:31 +02:00
There are several interesting ways to use Ansible from an API perspective. You can use
2013-10-05 19:50:53 +02:00
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.
2013-10-06 03:19:19 +02:00
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 :doc:`tower`
2013-10-05 19:50:53 +02:00
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.
.. _python_api:
2012-03-08 19:36:47 +01:00
The Python API is very powerful, and is how the ansible CLI and ansible-playbook
2015-12-02 07:41:23 +01:00
are implemented. In version 2.0 the core ansible got rewritten and the API was mostly rewritten.
.. _python_api_20:
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::
#!/usr/bin/python2
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play 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')
variable_manager.set_inventory(inventory)
# create play with tasks
play_source = dict(
name = "Ansible Play",
hosts = 'localhost',
gather_facts = 'no',
tasks = [ dict(action=dict(module='debug', args=dict(msg='Hello Galaxy!'))) ]
2015-12-02 07:41:23 +01:00
)
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
# actually run it
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback='default',
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
.. _python_api_old:
Python API pre 2.0
------------------
2012-03-08 19:36:47 +01:00
It's pretty simple::
import ansible.runner
runner = ansible.runner.Runner(
module_name='ping',
module_args='',
pattern='web*',
forks=10
)
datastructure = runner.run()
The run method returns results per host, grouped by whether they
could be contacted or not. Return types are module specific, as
2013-12-21 08:06:38 +01:00
expressed in the :doc:`modules` documentation.::
2012-03-08 19:36:47 +01:00
{
"dark" : {
"web1.example.com" : "failure message"
2013-04-11 06:43:16 +02:00
},
2012-03-08 19:36:47 +01:00
"contacted" : {
"web2.example.com" : 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.
2015-12-02 07:41:23 +01:00
.. _detailed_api_old_example:
2012-03-09 13:42:53 +01:00
Detailed API Example
````````````````````
The following script prints out the uptime information for all hosts::
#!/usr/bin/python
import ansible.runner
import sys
# construct the ansible runner and execute on all hosts
results = ansible.runner.Runner(
pattern='*', forks=10,
2012-08-25 01:33:14 +02:00
module_name='command', module_args='/usr/bin/uptime',
2012-03-09 13:42:53 +01:00
).run()
if results is None:
print "No hosts found"
sys.exit(1)
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)
2015-12-02 07:41:23 +01:00
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/``).
2012-03-09 13:42:53 +01:00
.. seealso::
:doc:`developing_inventory`
Developing dynamic inventory integrations
:doc:`developing_modules`
How to develop modules
:doc:`developing_plugins`
How to develop plugins
`Development Mailing List <http://groups.google.com/group/ansible-devel>`_
Mailing list for development topics
`irc.freenode.net <http://irc.freenode.net>`_
#ansible IRC chat channel