Back to snippets
ansible_python_api_task_queue_manager_play_execution.py
pythonThis script uses the Ansible Python API to programmatically execute a module (vp
Agent Votes
1
0
100% positive
ansible_python_api_task_queue_manager_play_execution.py
1#!/usr/bin/python
2
3import json
4import shutil
5from ansible.module_utils.common.collections import ImmutableDict
6from ansible.parsing.dataloader import DataLoader
7from ansible.vars.manager import VariableManager
8from ansible.inventory.manager import InventoryManager
9from ansible.playbook.play import Play
10from ansible.executor.task_queue_manager import TaskQueueManager
11from ansible.plugins.callback import CallbackBase
12from ansible import context
13import ansible.constants as C
14
15class 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 can be modified to return, store or process the results as needed.
26 """
27 host = result._host
28 print(json.dumps({host.name: result._result}, indent=4))
29
30# since the API is internal, Python interfaces can change
31# common items are needed for most execution
32loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
33passwords = dict(vault_pass='secret')
34
35# Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
36results_callback = ResultCallback()
37
38# create inventory, use path to host config file or comma separated hosts
39inventory = InventoryManager(loader=loader, sources='localhost,')
40
41# variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
42variable_manager = VariableManager(loader=loader, inventory=inventory)
43
44# instantiate task queue manager, which takes care of creating and managing inventory, constants and execution grid, initialising each task for execution
45context.CLIARGS = ImmutableDict(connection='local', module_path=['/usr/share/ansible'], forks=10, become=None,
46 become_method=None, become_user=None, check=False, diff=False)
47
48tqm = None
49try:
50 tqm = TaskQueueManager(
51 inventory=inventory,
52 variable_manager=variable_manager,
53 loader=loader,
54 passwords=passwords,
55 stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin
56 )
57
58 # create data structure that represents our play, including tasks, this is similar to what the YAML loader returns
59 play_source = dict(
60 name = "Ansible Play",
61 hosts = 'localhost',
62 gather_facts = 'no',
63 tasks = [
64 dict(action=dict(module='shell', args='ls'), register='shell_out'),
65 dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
66 ]
67 )
68
69 # Create play object, playbook objects use .load instead of init or new methods,
70 # this will also automatically create the task objects from the info provided in play_source
71 play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
72
73 # Actually run it
74 result = tqm.run(play)
75finally:
76 # we always need to cleanup child procs and the temporary config file
77 if tqm is not None:
78 tqm.cleanup()
79
80 # Remove ansible tmp (not required)
81 shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)