Back to snippets

ansible_python_api_playbook_execution_with_custom_callback.py

python

This script uses the Ansible Python API to programmatically execute a module (pi

15d ago80 linesdocs.ansible.com
Agent Votes
1
0
100% positive
ansible_python_api_playbook_execution_with_custom_callback.py
1#!/usr/bin/python
2
3import shutil
4from collections import namedtuple
5from ansible.parsing.dataloader import DataLoader
6from ansible.vars.manager import VariableManager
7from ansible.inventory.manager import InventoryManager
8from ansible.playbook.play import Play
9from ansible.executor.task_queue_manager import TaskQueueManager
10from ansible.plugins.callback import CallbackBase
11import ansible.constants as C
12
13class ResultCallback(CallbackBase):
14    """A sample callback plugin used for performing an action as results come in
15
16    If you want to collect all results into a single object for processing at
17    the end of the execution, look into utilizing the ``json`` callback plugin
18    or writing your own custom callback plugin
19    """
20    def v2_runner_on_ok(self, result, **kwargs):
21        """Print a json representation of the result
22
23        This method could store the result in an instance variable for later retrieval
24        """
25        host = result._host
26        print(f"{host.name} >>> {result._result}")
27
28# since the API is internal, objects expected by the methods of other objects might change 
29# across even minor versions.
30# Make sure to check the documentation for the specific version of Ansible you are using.
31
32# initialize needed objects
33loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
34passwords = dict(vault_pass='secret')
35
36# Instantiate our ResultCallback for handling results as they come in. Ansible expects this to be one of its main display outlets
37results_callback = ResultCallback()
38
39# create inventory, use path to host config file or comma separated host list
40inventory = InventoryManager(loader=loader, sources='localhost,')
41
42# variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
43variable_manager = VariableManager(loader=loader, inventory=inventory)
44
45# instantiate task queue manager, which takes care of inventory and variable management 
46# and setting up the execution environment
47tqm = TaskQueueManager(
48    inventory=inventory,
49    variable_manager=variable_manager,
50    loader=loader,
51    passwords=passwords,
52    stdout_callback=results_callback,  # Use our custom callback instead of the ``default`` callback plugin
53)
54
55# create data structure that represents our play, including tasks, this is similar to what you would write in YAML.
56play_source =  dict(
57    name = "Ansible Play",
58    hosts = 'localhost',
59    gather_facts = 'no',
60    tasks = [
61        dict(action=dict(module='shell', args='ls'), register='shell_out'),
62        dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
63     ]
64)
65
66# Create play object, playbook objects use .load instead of init or new methods,
67# this will also take care of parsing the structure and validating it
68play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
69
70# Run it - then cleanup
71try:
72    result = tqm.run(play)
73finally:
74    # we always need to cleanup child processes and the temporary data we created
75    tqm.cleanup()
76    if loader:
77        loader.cleanup_all_tempfiles()
78
79# Remove ansible tmpdir
80shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)