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 ansible.module_utils.common.collections import ImmutableDict
  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. from ansible import context
  13. import ansible.constants as C
  14.  
  15. class ResultCallback(CallbackBase):
  16. """A sample callback plugin used for performing an action as results come in
  17.  
  18. If you want to collect all results into a single object for processing at
  19. the end of the execution, look into utilizing the ``json`` callback plugin
  20. or writing your own custom callback plugin
  21. """
  22. def v2_runner_on_ok(self, result, **kwargs):
  23. """Print a json representation of the result
  24.  
  25. This method could store the result in an instance attribute for retrieval later
  26. """
  27. host = result._host
  28. print(json.dumps({host.name: result._result}, indent=4))
  29.  
  30. # since the API is constructed for CLI it expects certain options to always be set in the context object
  31. context.CLIARGS = ImmutableDict(connection='local', module_path=['/to/mymodules'], forks=10, become=None,
  32. become_method=None, become_user=None, check=False, diff=False)
  33.  
  34. # initialize needed objects
  35. loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
  36. passwords = dict(vault_pass='secret')
  37.  
  38. # Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
  39. results_callback = ResultCallback()
  40.  
  41. # create inventory, use path to host config file as source or hosts in a comma separated string
  42. inventory = InventoryManager(loader=loader, sources='localhost,')
  43.  
  44. # variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
  45. variable_manager = VariableManager(loader=loader, inventory=inventory)
  46.  
  47. # create data structure that represents our play, including tasks, this is basically what our YAML loader does internally.
  48. play_source = dict(
  49. name = "Ansible Play",
  50. hosts = 'localhost',
  51. gather_facts = 'no',
  52. tasks = [
  53. dict(action=dict(module='shell', args='ls'), register='shell_out'),
  54. dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
  55. ]
  56. )
  57.  
  58. # Create play object, playbook objects use .load instead of init or new methods,
  59. # this will also automatically create the task objects from the info provided in play_source
  60. play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
  61.  
  62. # Run it - instantiate task queue manager, which takes care of forking and setting up all objects to iterate over host list and tasks
  63. tqm = None
  64. try:
  65. tqm = TaskQueueManager(
  66. inventory=inventory,
  67. variable_manager=variable_manager,
  68. loader=loader,
  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 structures 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