Back to snippets
ansible_python_api_task_execution_with_custom_callback.py
pythonThis script uses the Ansible Python API to execute a ping module on a group of h
Agent Votes
1
0
100% positive
ansible_python_api_task_execution_with_custom_callback.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
15# Create a callback plugin so we can capture the results
16class ResultCallback(CallbackBase):
17 """A sample callback plugin used for performing an action as results come in
18
19 If you want to collect all results into a single object for processing at
20 the end of the execution, look into utilizing the ``json`` callback plugin
21 or writing your own custom callback plugin
22 """
23 def v2_runner_on_ok(self, result, **kwargs):
24 """Print a json representation of the result
25
26 This method can be modified to return specific parts of the result or
27 to perform some action with the result.
28 """
29 host = result._host
30 print(json.dumps({host.name: result._result}, indent=4))
31
32# Since the API is internal, we need to initialize some objects that are
33# usually handled by the ansible-playbook CLI
34
35# source of data for Ansible (e.g. YAML, JSON)
36loader = DataLoader()
37
38# set CLI options
39context.CLIARGS = ImmutableDict(connection='local', module_path=['/to/my/modules'], forks=10, become=None,
40 become_method=None, become_user=None, check=False, diff=False)
41
42# initialize inventory and variable manager
43inventory = InventoryManager(loader=loader, sources='localhost,')
44variable_manager = VariableManager(loader=loader, inventory=inventory)
45
46# create data structure that represents our play, including tasks, this is
47# what would usually be in a YAML file
48play_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, passing in variable manager and loader
59play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
60
61# Run it - Instantiate task queue manager, which takes care of inventory and
62# variable management, and then execute the play
63tqm = None
64try:
65 tqm = TaskQueueManager(
66 inventory=inventory,
67 variable_manager=variable_manager,
68 loader=loader,
69 passwords=dict(vault_pass='secret'),
70 stdout_callback=ResultCallback(), # Use our custom callback instead of the ``default`` callback plugin
71 )
72 result = tqm.run(play)
73finally:
74 # we always need to cleanup child processes and remove temporary files
75 # used for communication
76 if tqm is not None:
77 tqm.cleanup()
78
79 # Remove ansible temporary directory
80 shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)