python执行ad_hoc
1 import shutil 2 from collections import namedtuple 3 from ansible.parsing.dataloader import DataLoader 4 from ansible.vars.manager import VariableManager 5 from ansible.inventory.manager import InventoryManager 6 from ansible.playbook.play import Play 7 from ansible.executor.task_queue_manager import TaskQueueManager 8 import ansible.constants as C 9 10 def ad_hoc(inventory_fname, hosts, module, args): 11 Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff']) 12 options = Options(connection='ssh', module_path=[''], forks=10, become=None, become_method=None, become_user=None, check=False, diff=False) 13 loader = DataLoader() 14 passwords = dict() 15 inventory = InventoryManager(loader=loader, sources=inventory_fname) 16 variable_manager = VariableManager(loader=loader, inventory=inventory) 17 play_source=dict( 18 name="my ansible play", 19 hosts=hosts, 20 gather_facts='no', 21 tasks=[ 22 dict(action=dict(module=module, args=args), register='shell_out'), 23 dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}'))) 24 ] 25 ) 26 play = Play().load(play_source, variable_manager=variable_manager, loader=loader) 27 28 tqm = None 29 try: 30 tqm = TaskQueueManager( 31 inventory=inventory, 32 variable_manager=variable_manager, 33 loader=loader, 34 options=options, 35 passwords=passwords, 36 ) 37 result = tqm.run(play) 38 finally: 39 if tqm is not None: 40 tqm.cleanup() 41 42 shutil.rmtree(C.DEFAULT_LOCAL_TMP, True) 43 44 if __name__ == '__main__': 45 inventory_fname = ['myansible/hosts'] 46 hosts = "webservers" 47 module = "shell" 48 args = "ls -ld /home" 49 ad_hoc(inventory_fname, hosts, module, args) 50 ad_hoc(inventory_fname, 'dbservers', module, 'mkdir /tmp/mydemo')