PageRenderTime 54ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/docsite/rst/developing_api.rst

https://gitlab.com/0072016/Facebook-SDK-json-
ReStructuredText | 194 lines | 147 code | 47 blank | 0 comment | 0 complexity | a5f7228a283686e66279a9c55d6e3db4 MD5 | raw file
  1. Python API
  2. ==========
  3. .. contents:: Topics
  4. Please note that while we make this API available it is not intended for direct consumption, it is here
  5. for the support of the Ansible command line tools. We try not to make breaking changes but we reserve the
  6. right to do so at any time if it makes sense for the Ansible toolset.
  7. The following documentation is provided for those that still want to use the API directly, but be mindful this is not something the Ansible team supports.
  8. There are several interesting ways to use Ansible from an API perspective. You can use
  9. the Ansible python API to control nodes, you can extend Ansible to respond to various python events, you can
  10. write various plugins, and you can plug in inventory data from external data sources. This document
  11. covers the execution and Playbook API at a basic level.
  12. If you are looking to use Ansible programmatically from something other than Python, trigger events asynchronously,
  13. or have access control and logging demands, take a look at :doc:`tower`
  14. as it has a very nice REST API that provides all of these things at a higher level.
  15. Ansible is written in its own API so you have a considerable amount of power across the board.
  16. This chapter discusses the Python API.
  17. .. _python_api:
  18. The Python API is very powerful, and is how the all the ansible CLI tools are implemented.
  19. In version 2.0 the core ansible got rewritten and the API was mostly rewritten.
  20. .. note:: Ansible relies on forking processes, as such the API is not thread safe.
  21. .. _python_api_20:
  22. Python API 2.0
  23. --------------
  24. In 2.0 things get a bit more complicated to start, but you end up with much more discrete and readable classes::
  25. #!/usr/bin/env python
  26. import json
  27. from collections import namedtuple
  28. from ansible.parsing.dataloader import DataLoader
  29. from ansible.vars import VariableManager
  30. from ansible.inventory import Inventory
  31. from ansible.playbook.play import Play
  32. from ansible.executor.task_queue_manager import TaskQueueManager
  33. from ansible.plugins.callback import CallbackBase
  34. class ResultCallback(CallbackBase):
  35. """A sample callback plugin used for performing an action as results come in
  36. If you want to collect all results into a single object for processing at
  37. the end of the execution, look into utilizing the ``json`` callback plugin
  38. or writing your own custom callback plugin
  39. """
  40. def v2_runner_on_ok(self, result, **kwargs):
  41. """Print a json representation of the result
  42. This method could store the result in an instance attribute for retrieval later
  43. """
  44. host = result._host
  45. print json.dumps({host.name: result._result}, indent=4)
  46. Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check'])
  47. # initialize needed objects
  48. variable_manager = VariableManager()
  49. loader = DataLoader()
  50. options = Options(connection='local', module_path='/path/to/mymodules', forks=100, become=None, become_method=None, become_user=None, check=False)
  51. passwords = dict(vault_pass='secret')
  52. # Instantiate our ResultCallback for handling results as they come in
  53. results_callback = ResultCallback()
  54. # create inventory and pass to var manager
  55. inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list='localhost')
  56. variable_manager.set_inventory(inventory)
  57. # create play with tasks
  58. play_source = dict(
  59. name = "Ansible Play",
  60. hosts = 'localhost',
  61. gather_facts = 'no',
  62. tasks = [
  63. dict(action=dict(module='shell', args='ls'), register='shell_out'),
  64. dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
  65. ]
  66. )
  67. play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
  68. # actually run it
  69. tqm = None
  70. try:
  71. tqm = TaskQueueManager(
  72. inventory=inventory,
  73. variable_manager=variable_manager,
  74. loader=loader,
  75. options=options,
  76. passwords=passwords,
  77. stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin
  78. )
  79. result = tqm.run(play)
  80. finally:
  81. if tqm is not None:
  82. tqm.cleanup()
  83. .. _python_api_old:
  84. Python API pre 2.0
  85. ------------------
  86. It's pretty simple::
  87. import ansible.runner
  88. runner = ansible.runner.Runner(
  89. module_name='ping',
  90. module_args='',
  91. pattern='web*',
  92. forks=10
  93. )
  94. datastructure = runner.run()
  95. The run method returns results per host, grouped by whether they
  96. could be contacted or not. Return types are module specific, as
  97. expressed in the :doc:`modules` documentation.::
  98. {
  99. "dark" : {
  100. "web1.example.com" : "failure message"
  101. },
  102. "contacted" : {
  103. "web2.example.com" : 1
  104. }
  105. }
  106. A module can return any type of JSON data it wants, so Ansible can
  107. be used as a framework to rapidly build powerful applications and scripts.
  108. .. _detailed_api_old_example:
  109. Detailed API Example
  110. ````````````````````
  111. The following script prints out the uptime information for all hosts::
  112. #!/usr/bin/python
  113. import ansible.runner
  114. import sys
  115. # construct the ansible runner and execute on all hosts
  116. results = ansible.runner.Runner(
  117. pattern='*', forks=10,
  118. module_name='command', module_args='/usr/bin/uptime',
  119. ).run()
  120. if results is None:
  121. print "No hosts found"
  122. sys.exit(1)
  123. print "UP ***********"
  124. for (hostname, result) in results['contacted'].items():
  125. if not 'failed' in result:
  126. print "%s >>> %s" % (hostname, result['stdout'])
  127. print "FAILED *******"
  128. for (hostname, result) in results['contacted'].items():
  129. if 'failed' in result:
  130. print "%s >>> %s" % (hostname, result['msg'])
  131. print "DOWN *********"
  132. for (hostname, result) in results['dark'].items():
  133. print "%s >>> %s" % (hostname, result)
  134. Advanced programmers may also wish to read the source to ansible itself,
  135. for it uses the API (with all available options) to implement the ``ansible``
  136. command line tools (``lib/ansible/cli/``).
  137. .. seealso::
  138. :doc:`developing_inventory`
  139. Developing dynamic inventory integrations
  140. :doc:`developing_modules`
  141. How to develop modules
  142. :doc:`developing_plugins`
  143. How to develop plugins
  144. `Development Mailing List <http://groups.google.com/group/ansible-devel>`_
  145. Mailing list for development topics
  146. `irc.freenode.net <http://irc.freenode.net>`_
  147. #ansible IRC chat channel