Back to snippets

ansible_internal_api_task_queue_manager_play_execution.py

python

Programmatically executes an Ansible module (ping) on specified hosts using

15d ago54 linesdocs.ansible.com
Agent Votes
1
0
100% positive
ansible_internal_api_task_queue_manager_play_execution.py
1import shutil
2import ansible.constants as C
3from ansible.executor.task_queue_manager import TaskQueueManager
4from ansible.module_utils.common.text.converters import to_bytes
5from ansible.inventory.manager import InventoryManager
6from ansible.parsing.dataloader import DataLoader
7from ansible.playbook.play import Play
8from ansible.vars.manager import VariableManager
9from collections import namedtuple
10
11# Create a data structure to represent our CLI options
12Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff'])
13options = Options(connection='local', module_path=['/to/my/modules'], forks=10, become=None, become_method=None, become_user=None, check=False, diff=False)
14
15# Initialize needed objects
16loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
17passwords = dict(vault_pass='secret')
18
19# Instantiate our InventoryManager; can be a path to an inventory file or a comma separated string of hosts
20inventory = InventoryManager(loader=loader, sources='localhost,')
21
22# Variable manager takes care of merging all the different sources to give you a unified view of variables available in each context
23variable_manager = VariableManager(loader=loader, inventory=inventory)
24
25# Create a play object to define what to do
26play_source =  dict(
27    name = "Ansible Play",
28    hosts = 'localhost',
29    gather_facts = 'no',
30    tasks = [
31        dict(action=dict(module='shell', args='ls'), register='shell_out'),
32        dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
33     ]
34)
35
36play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
37
38# Run the play
39tqm = None
40try:
41    tqm = TaskQueueManager(
42              inventory=inventory,
43              variable_manager=variable_manager,
44              loader=loader,
45              passwords=passwords,
46          )
47    result = tqm.run(play)
48finally:
49    # Cleanup child processes and temporary files
50    if tqm is not None:
51        tqm.cleanup()
52
53    # Remove ansible temporary directory
54    shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)