Python API

Note

This API is intended for internal Ansible use. Ansible may make changes to this API at any time that could break backward compatibility with older versions of the API. Because of this, external use is not supported by Ansible.

There are several ways to use Ansible from an API perspective. You can usethe Ansible Python API to control nodes, you can extend Ansible to respond to various Python events, you canwrite plugins, and you can plug in inventory data from external data sources. This documentgives a basic overview and examples of the Ansible execution and playbook API.

If you would like to use Ansible programmatically from a language other than Python, trigger events asynchronously,or have access control and logging demands, please see the Ansible Tower documentation.

Note

Because Ansible relies on forking processes, this API is not thread safe.

Python API example

This example is a simple demonstration that shows how to minimally run a couple of tasks:

  1. #!/usr/bin/env python
  2.  
  3. import json
  4. import shutil
  5. from collections import namedtuple
  6. from ansible.parsing.dataloader import DataLoader
  7. from ansible.vars.manager import VariableManager
  8. from ansible.inventory.manager import InventoryManager
  9. from ansible.playbook.play import Play
  10. from ansible.executor.task_queue_manager import TaskQueueManager
  11. from ansible.plugins.callback import CallbackBase
  12. import ansible.constants as C
  13.  
  14. class ResultCallback(CallbackBase):
  15. """A sample callback plugin used for performing an action as results come in
  16.  
  17. If you want to collect all results into a single object for processing at
  18. the end of the execution, look into utilizing the ``json`` callback plugin
  19. or writing your own custom callback plugin
  20. """
  21. def v2_runner_on_ok(self, result, **kwargs):
  22. """Print a json representation of the result
  23.  
  24. This method could store the result in an instance attribute for retrieval later
  25. """
  26. host = result._host
  27. print(json.dumps({host.name: result._result}, indent=4))
  28.  
  29. # since API is constructed for CLI it expects certain options to always be set, named tuple 'fakes' the args parsing options object
  30. Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff'])
  31. options = Options(connection='local', module_path=['/to/mymodules'], forks=10, become=None, become_method=None, become_user=None, check=False, diff=False)
  32.  
  33. # initialize needed objects
  34. loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
  35. passwords = dict(vault_pass='secret')
  36.  
  37. # Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
  38. results_callback = ResultCallback()
  39.  
  40. # create inventory, use path to host config file as source or hosts in a comma separated string
  41. inventory = InventoryManager(loader=loader, sources='localhost,')
  42.  
  43. # variable manager takes care of merging all the different sources to give you a unifed view of variables available in each context
  44. variable_manager = VariableManager(loader=loader, inventory=inventory)
  45.  
  46. # create datastructure that represents our play, including tasks, this is basically what our YAML loader does internally.
  47. play_source = dict(
  48. name = "Ansible Play",
  49. hosts = 'localhost',
  50. gather_facts = 'no',
  51. tasks = [
  52. dict(action=dict(module='shell', args='ls'), register='shell_out'),
  53. dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
  54. ]
  55. )
  56.  
  57. # Create play object, playbook objects use .load instead of init or new methods,
  58. # this will also automatically create the task objects from the info provided in play_source
  59. play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
  60.  
  61. # Run it - instantiate task queue manager, which takes care of forking and setting up all objects to iterate over host list and tasks
  62. tqm = None
  63. try:
  64. tqm = TaskQueueManager(
  65. inventory=inventory,
  66. variable_manager=variable_manager,
  67. loader=loader,
  68. options=options,
  69. passwords=passwords,
  70. stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin, which prints to stdout
  71. )
  72. result = tqm.run(play) # most interesting data for a play is actually sent to the callback's methods
  73. finally:
  74. # we always need to cleanup child procs and the structres we use to communicate with them
  75. if tqm is not None:
  76. tqm.cleanup()
  77.  
  78. # Remove ansible tmpdir
  79. shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

Note

Ansible emits warnings and errors via the display object, which prints directly to stdout, stderr and the Ansible log.

The source code for the ansiblecommand line tools (lib/ansible/cli/) is available on Github.

See also