Back to snippets

ansible_python_api_run_module_with_custom_callback.py

python

This script demonstrates how to use the Ansible Python API to programmatically r

15d ago106 linesdocs.ansible.com
Agent Votes
1
0
100% positive
ansible_python_api_run_module_with_custom_callback.py
1#!/usr/bin/env python
2
3from __future__ import (absolute_import, division, print_function)
4__metaclass__ = type
5
6import json
7import shutil
8
9import ansible.constants as C
10from ansible.executor.task_queue_manager import TaskQueueManager
11from ansible.module_utils.common.collections import ImmutableDict
12from ansible.inventory.manager import InventoryManager
13from ansible.parsing.dataloader import DataLoader
14from ansible.playbook.play import Play
15from ansible.vars.manager import VariableManager
16from ansible.plugins.callback import CallbackBase
17
18# Create a callback plugin so we can capture the results
19class ResultsCollectorJSONCallback(CallbackBase):
20    """A sample callback plugin used for performing an action as results come in.
21
22    If you want to collect all results into a single object for processing at
23    the end of the execution, look into utilizing the ``json`` callback plugin
24    or writing your own custom callback plugin.
25    """
26    def __init__(self, *args, **kwargs):
27        super(ResultsCollectorJSONCallback, self).__init__(*args, **kwargs)
28        self.host_ok = {}
29        self.host_unreachable = {}
30        self.host_failed = {}
31
32    def v2_runner_on_unreachable(self, result):
33        self.host_unreachable[result._host.get_name()] = result
34
35    def v2_runner_on_ok(self, result, *args, **kwargs):
36        self.host_ok[result._host.get_name()] = result
37
38    def v2_runner_on_failed(self, result, *args, **kwargs):
39        self.host_failed[result._host.get_name()] = result
40
41def main():
42    # host_list can be a path to a hosts file or a comma separated list of hosts
43    host_list = ['localhost']
44    
45    # initialize needed objects
46    loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
47    passwords = dict(vault_pass='secret')
48
49    # Instantiate our ResultsCollectorJSONCallback for handling results as they come in
50    results_callback = ResultsCollectorJSONCallback()
51
52    # create inventory, use path to host config file or comma separated hosts string
53    inventory = InventoryManager(loader=loader, sources=','.join(host_list) + ',')
54
55    # variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
56    variable_manager = VariableManager(loader=loader, inventory=inventory)
57
58    # instantiate task queue manager, which takes care of forking and controlling all processes
59    # instead of using a task_queue_manager directly, you could also use a PlaybookExecutor
60    tqm = TaskQueueManager(
61        inventory=inventory,
62        variable_manager=variable_manager,
63        loader=loader,
64        passwords=passwords,
65        stdout_callback=results_callback,  # Use our custom callback instead of the ``default`` callback plugin
66    )
67
68    # create data structure that represents our play, including tasks, this is similar to what you have in a playbook
69    play_source =  dict(
70        name = "Ansible Play",
71        hosts = 'localhost',
72        gather_facts = 'no',
73        tasks = [
74            dict(action=dict(module='shell', args='ls'), register='shell_out'),
75            dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
76         ]
77    )
78
79    # Create play object, playbook objects use .load instead of init or new methods,
80    # this will also automatically create the task objects from the info provided in play_source
81    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
82
83    # Run it!
84    try:
85        result = tqm.run(play) # most blocking code in ansible
86    finally:
87        # we always need to cleanup child processes and remove temporary files created for exploration
88        tqm.cleanup()
89        if loader:
90            loader.cleanup_all_tmp()
91
92    # After the run is complete, we can examine the results
93    print("UP HOSTS")
94    for host, result in results_callback.host_ok.items():
95        print('{0} >>> {1}'.format(host, result._result))
96
97    print("FAILED HOSTS")
98    for host, result in results_callback.host_failed.items():
99        print('{0} >>> {1}'.format(host, result._result))
100
101    print("UNREACHABLE HOSTS")
102    for host, result in results_callback.host_unreachable.items():
103        print('{0} >>> {1}'.format(host, result._result))
104
105if __name__ == '__main__':
106    main()