def run(self, tasks, pattern, play_name='Ansible Ad-hoc', gather_facts='no'): """ :param tasks: [{'action': {'module': 'shell', 'args': 'ls'}, ...}, ] :param pattern: all, *, or others :param play_name: The play name :param gather_facts: :return: """ self.check_pattern(pattern) self.results_callback = self.get_result_callback() cleaned_tasks = self.clean_tasks(tasks) play_source = dict( name=play_name, hosts=pattern, gather_facts=gather_facts, tasks=cleaned_tasks ) play = Play().load( play_source, variable_manager=self.variable_manager, loader=self.loader, ) tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, stdout_callback=self.results_callback, passwords=self.options.passwords, ) try: tqm.run(play) return self.results_callback except Exception as e: raise AnsibleError(e) finally: tqm.cleanup() self.loader.cleanup_all_tmp_files()
def test_strategy_base_queue_task(self, mock_worker): def fake_run(self): return mock_worker.run.side_effect = fake_run fake_loader = DictDataLoader() mock_var_manager = MagicMock() mock_host = MagicMock() mock_host.get_vars.return_value = dict() mock_host.has_hostkey = True mock_inventory = MagicMock() mock_inventory.get.return_value = mock_host tqm = TaskQueueManager( inventory=mock_inventory, variable_manager=mock_var_manager, loader=fake_loader, passwords=None, forks=3, ) tqm._initialize_processes(3) tqm.hostvars = dict() mock_task = MagicMock() mock_task._uuid = 'abcd' mock_task.throttle = 0 try: strategy_base = StrategyBase(tqm=tqm) strategy_base._queue_task(host=mock_host, task=mock_task, task_vars=dict(), play_context=MagicMock()) self.assertEqual(strategy_base._cur_worker, 1) self.assertEqual(strategy_base._pending_results, 1) strategy_base._queue_task(host=mock_host, task=mock_task, task_vars=dict(), play_context=MagicMock()) self.assertEqual(strategy_base._cur_worker, 2) self.assertEqual(strategy_base._pending_results, 2) strategy_base._queue_task(host=mock_host, task=mock_task, task_vars=dict(), play_context=MagicMock()) self.assertEqual(strategy_base._cur_worker, 0) self.assertEqual(strategy_base._pending_results, 3) finally: tqm.cleanup()
def exec_task(target, mod, args, inventory_path=['ansicfg/dhosts.py']): Options = namedtuple('Options', [ 'connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff' ]) options = Options(connection='smart', module_path=['/to/mymodules'], forks=10, become=None, become_method=None, become_user=None, check=False, diff=False) loader = DataLoader() passwords = dict() inventory = InventoryManager(loader=loader, sources=inventory_path) variable_manager = VariableManager(loader=loader, inventory=inventory) play_source = dict(name="Ansible Play", hosts=target, gather_facts='no', tasks=[ dict(action=dict(module=mod, args=args), register='shell_out'), ]) play = Play().load(play_source, variable_manager=variable_manager, loader=loader) tqm = None try: tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords, ) result = tqm.run(play) finally: if tqm is not None: tqm.cleanup() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
def run_play(play_ds, inventory_file, loader, remote_user, remote_pass, transport, extra_vars=None): variable_manager = get_variable_manager(loader) variable_manager.extra_vars = {} if extra_vars is None else extra_vars loader._FILE_CACHE = dict() # clean up previously read and cached files inv = get_inventory(loader=loader, variable_manager=variable_manager, inventory_file=inventory_file) variable_manager.set_inventory(inv) play = Play.load(play_ds, variable_manager=variable_manager, loader=loader) tqm = None result = 1 try: options = default_options(remote_user, transport) display.verbosity = options.verbosity tqm = TaskQueueManager( inventory=inv, variable_manager=variable_manager, loader=loader, options=options, passwords={'conn_pass': remote_pass} if remote_pass else {}, stdout_callback='minimal', run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS, run_tree=False, ) result = tqm.run(play) except Exception as ex: io.track_error('cannot run play', ex) finally: if tqm: tqm.cleanup() return result == 0
def run_adhoc(ip, order): variable_manager.extra_vars = { "ansible_ssh_user": "******", "ansible_ssh_pass": "******" } play_source = { "name": "Ansible Ad-Hoc", "hosts": "%s" % ip, "gather_facts": "no", "tasks": [{ "action": { "module": "command", "args": "%s" % order } }] } # play_source = {"name":"Ansible Ad-Hoc","hosts":"192.168.2.160","gather_facts":"no","tasks":[{"action":{"module":"command","args":"python ~/store.py del"}}]} play = Play().load(play_source, variable_manager=variable_manager, loader=loader) tqm = None callback = ResultsCollector() try: tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=None, #stdout_callback='minimal', #stdout_callback=results_callback, run_tree=False, ) tqm._stdout_callback = callback result = tqm.run(play) return callback finally: if tqm is not None: tqm.cleanup()
def run(self, play): tqm = None rc = ResultCallback() try: tqm = TaskQueueManager( inventory=self._inventory, variable_manager=self._variable_manager, loader=self._loader, passwords=dict(), stdout_callback=rc) tqm.run(play) finally: if tqm is not None: tqm.cleanup() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True) if rc.failed_playbook_run: raise AnsibleRunError( 'Unable to run playbook.', rc.result_playbook_run[-1]) return rc.result_playbook_run
def run(self): """Execute the playbook.""" # Instancia el objeto del playbook play = Play().load(self.playbook, variable_manager=self.variable_manager, loader=self.loader) # Añade el playbook a la cola tqm = TaskQueueManager(inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, stdout_callback=self.callback) # Ejecuta el playbook tqm.run(play) # Guarda los resultados de un modo mas accesible. Probablemente # mala practica, dado que accede a un metodo protegido. tqm = tqm._variable_manager._nonpersistent_fact_cache.items() return tqm
def __init__(self, playbooks, inventory, variable_manager, loader, options, passwords): self._playbooks = playbooks self._inventory = inventory self._variable_manager = variable_manager self._loader = loader self._options = options self.passwords = passwords self._unreachable_hosts = dict() if options.listhosts or options.listtasks or options.listtags or options.syntax: self._tqm = None else: self._tqm = TaskQueueManager(inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=self.passwords) # Note: We run this here to cache whether the default ansible ssh # executable supports control persist. Sometime in the future we may # need to enhance this to check that ansible_ssh_executable specified # in inventory is also cached. We can't do this caching at the point # where it is used (in task_executor) because that is post-fork and # therefore would be discarded after every task. check_for_controlpersist(C.ANSIBLE_SSH_EXECUTABLE)
def receive_source_run(self, source_dict): play = Play().load(source_dict, variable_manager=self.variable_manager, loader=self.loader) tqm = None try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, stdout_callback=self.results_callback, ) tqm.run(play) finally: if tqm is not None: tqm.cleanup() re = self.result_count() return re
def _run_task(cls, play, inventory, variable_manager, loader, options, canary, added_by, play_source, spath): """Runs the Playbook tasks with the required variables and managers.""" tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=dict(), stdout_callback=ResultCallback(canary, added_by, play_source, spath), ) result = tqm.run(play) if tqm is not None: tqm.cleanup() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True) return result
def _execute_play(play_source, inventory, var_mgr, loader, options, callback): # pylint: disable=too-many-arguments """ Execute the playbook """ play = Play().load(play_source, variable_manager=var_mgr, loader=loader) tqm = None try: tqm = TaskQueueManager( inventory=inventory, variable_manager=var_mgr, loader=loader, options=options, passwords=None, stdout_callback=callback, ) _ = tqm.run(play) except Exception as exc: raise TaskExecutionException(str(exc)) finally: if tqm is not None: tqm.cleanup()
def __init__(self, playbooks, inventory, variable_manager, loader, options, passwords, stdout_callback=None): self._playbooks = playbooks self._inventory = inventory self._variable_manager = variable_manager self._loader = loader self._options = options self.passwords = passwords self._unreachable_hosts = dict() if options.listhosts or options.listtasks or options.listtags or options.syntax: self._tqm = None else: self._tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=self.passwords, stdout_callback=stdout_callback) check_for_controlpersist(C.ANSIBLE_SSH_EXECUTABLE)
def run(self, hosts='all', gether_facts="no", module="ping", args=''): #定义一个字典,来设置主机组、是否获取机器信息、以及执行的模块及参数, #参数可以在执行run()函数的时候传入 play_source = dict( name="Ad-hoc", hosts=hosts, gather_facts=gether_facts, tasks=[ # 这里每个 task 就是这个列表中的一个元素,格式是嵌套的字典 # 也可以作为参数传递过来,这里就简单化了。 { "action": { "module": module, "args": args } }, ]) #Play()是用于执行 Ad-hoc 的类 ,这里传入一个上面的play_source字典参数 VariableManager变量管理器 DataLoader数据解析器 play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) # 先定义一个值,防止代码出错后, `finally` 语句中的 `tqm` 未定义。 tqm = None try: #TaskQueueManager是底层用到的任务队列管理器 #要想执行 Ad-hoc ,需要把上面的 play 对象交给任务队列管理器的 run 方法去运行 tqm = TaskQueueManager(inventory=self.inv_obj, variable_manager=self.variable_manager, loader=self.loader, passwords=self.passwords, stdout_callback=self.results_callback) result = tqm.run(play) finally: if tqm is not None: tqm.cleanup() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
def run_model(self, host_list, module_name, module_args): """ run module from andible ad-hoc. module_name: ansible module_name module_args: ansible module args """ play_source = dict( name="Ansible Play", hosts=host_list, gather_facts='no', tasks=[dict(action=dict(module=module_name, args=module_args))]) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None if self.redisKey or self.logId: self.callback = ModelResultsCollectorToSave( self.redisKey, self.logId) else: self.callback = ModelResultsCollector() try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, ) tqm._stdout_callback = self.callback constants.HOST_KEY_CHECKING = False #关闭第一次使用ansible连接客户端是输入命令 tqm.run(play) except Exception as err: logger.error(msg="run model failed: {err}".format(err=str(err))) if self.redisKey: DsRedis.OpsAnsibleModel.lpush(self.redisKey, data=err) if self.logId: AnsibleSaveResult.Model.insert(self.logId, err) finally: if tqm is not None: tqm.cleanup()
def run(self, host_list, moduls='shell', _args=None, **kwargs): if kwargs: parame = kwargs elif _args: parame = _args else: parame = {} play_source = dict(name="Ansible Play ad-hoc", hosts=host_list, gather_facts='no', tasks=[ dict(action=dict(module=moduls, args=parame)), ]) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) callback = ModelResultsCollector() passwords = dict() tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=passwords, stdout_callback=callback, ) result = tqm.run(play) result_raw = {'success': {}, 'failed': {}, 'unreachable': {}} for host, result in callback.host_unreachable.items(): result_raw['unreachable'][host] = result._result for host, result in callback.host_ok.items(): result_raw['success'][host] = result._result for host, result in callback.host_failed.items(): result_raw['failed'][host] = result._result return result_raw
def run_ad_hoc(self, host, module_name, module_args): """ run module from andible ad-hoc. module_name: ansible module_name module_args: ansible module args """ self.callback = AdHocResultCallback(self.uuid, self.sock) # create play with tasks play_source = dict( name="Ansible ad-hoc", hosts=host, gather_facts='no', tasks=[dict(action=dict(module=module_name, args=module_args))]) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) # actually run it tqm = None try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, ) tqm._stdout_callback = self.callback C.HOST_KEY_CHECKING = False tqm.run(play) except Exception as e: Task.objects.filter(id=self.task_id).update(error_msg=str(e), executed=True) finally: if tqm is not None: tqm.cleanup() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
def run(self, hosts="localhost", gether_facts="no", module="ping", args=""): play_source = dict( name="Ad-hoc", hosts=hosts, gather_facts=gether_facts, tasks=[ # 这里每个 task 就是这个列表中的一个元素,格式是嵌套的字典 # 也可以作为参数传递过来,这里就简单化了。 { "action": { "module": module, "args": args } } ], ) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None try: tqm = TaskQueueManager( inventory=self.inv_obj, variable_manager=self.variable_manager, loader=self.loader, passwords=self.passwords, stdout_callback=self.results_callback, ) result = tqm.run(play) finally: if tqm is not None: tqm.cleanup() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
def run_model(self, host_list, module_name, module_args): """ run module from ansible ad-hoc. module_name: ansible module_name module_args: ansible module args """ play_source = dict( name="Ansible Play", hosts=host_list, gather_facts='no', tasks=[dict(action=dict(module=module_name, args=module_args))]) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None # if self.redisKey:self.callback = ModelResultsCollectorToSave(self.redisKey,self.logId) # else:self.callback = ModelResultsCollector() self.callback = ModelResultsCollector() import traceback try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, stdout_callback="minimal", ) tqm._stdout_callback = self.callback constants.HOST_KEY_CHECKING = False #关闭第一次使用ansible连接客户端是输入命令 tqm.run(play) except Exception as err: print(traceback.print_exc()) # DsRedis.OpsAnsibleModel.lpush(self.redisKey,data=err) # if self.logId:AnsibleSaveResult.Model.insert(self.logId, err) finally: if tqm is not None: tqm.cleanup()
def run( self, host_list, module_name, module_args, ): """ run module from andible ad-hoc. module_name: ansible module_name module_args: ansible module args """ # create play with tasks play_source = dict( name="Ansible Play", hosts=host_list, gather_facts='no', tasks=[dict(action=dict(module=module_name, args=module_args))]) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) # actually run it tqm = None self.callback = ResultsCollector() try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, stdout_callback='default', ) tqm._stdout_callback = self.callback result = tqm.run(play) # print result # print self.callback finally: if tqm is not None: tqm.cleanup()
def __init__(self, pb_file, sources=['inventory/hosts'], **kwargs): self.pb_file = pb_file self.sources = sources Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff']) # initialize needed objects self.Options = Options(connection='smart', module_path=None, forks=100, become=True, become_method='sudo', become_user='******', check=False, diff=False) self.loader = DataLoader() passwords = dict(vault_pass='******') # Instantiate our ResultCallback for handling results as they come in self.results_callback = ResultCallback() # create inventory and pass to var manager #self.inventory = InventoryManager(loader=loader, sources=['/home/alvin/git/ansible/ansible-playbook/inventory/hosts']) self.inventory = self._gen_inventory() self.variable_manager = VariableManager(loader=self.loader, inventory=self.inventory) self.variable_manager.extra_vars = kwargs self.tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.Options, passwords=passwords, stdout_callback=self.results_callback, )
def run_play(self, host_list, module_name, module_args): """ run play :param host_list is list, :param module_name is string :param module_args is string """ play = None # create play with tasks play_source = dict( name="Ansible Play", hosts=host_list, gather_facts='no', tasks=[dict(action=dict(module=module_name, args=module_args))]) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) # actually run it tqm = None display = LogDisplay(logname=self.job_id) callback = CALLBACKMODULE[CALLBACK](display=display) if module_name == 'backup': # 对于备份模块,特殊处理,必须使用minimal,才能获取到文件名属性 callback = minimal_callback(display=display) try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, ) tqm._stdout_callback = callback tqm.run(play) finally: if tqm is not None: tqm.cleanup() return display.get_log_json()
def run(self): tqm = None try: tqm = TaskQueueManager(inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords={}, stdout_callback=self.stdout_callback) from deveops.asgi import channel_layer channel_layer.send(self.replay_name, {'text': 'Start => \r\n'}) for p in self.play: result = tqm.run(p) # self.delete_key() channel_layer.send(self.replay_name, {'text': u'执行完毕\r\n'}) channel_layer.send(self.replay_name, {'close': True}) finally: if tqm is not None: tqm.cleanup()
def run_playbook(play, variable_manager=None, inventory_manager=None, loader=None, passwords=None): result = -1 try: tqm = TaskQueueManager( inventory=inventory_manager, variable_manager=variable_manager, loader=loader, passwords=passwords, ) result = tqm.run(play) finally: if tqm is not None: tqm.cleanup() if loader: loader.cleanup_all_tmp_files() if result == 0: return True return False
def play_task(self, module, args, task_name, function): results_callback = ResultCallback(display=None, options=None, task_name=task_name, result_function=function) play_source = dict( name=task_name, hosts='all', gather_facts='no', tasks=[ dict(action=dict(module=module, args=args), register='shell_out'), #dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}'))) ]) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, stdout_callback=results_callback, ) result = tqm.run(play) except Exception as e: now = datetime.datetime.now() print( datetime.datetime.strftime(now, "%Y.%m.%d %H:%M:%S") + ":" + e) # else: # return True finally: if tqm is not None: tqm.cleanup() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
def run(self, host_list, module_name, module_args=None): # 创建任务 play_source = dict( name="Ansible Play", hosts=host_list, gather_facts='no', tasks=[ dict( action=dict( module=module_name, args=module_args ) ), # dict(action=dict(module='shell', args="id"), register='shell_out'), # dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')), async=0, poll=15) ] ) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) # 实际运行 # TaskQueueManager 是创建进程池, 负责输出结果和多进程间数据结构或者队列的共享协作 tqm = None # 结果回调类实例化 self.callback = ResultsCollector() try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, stdout_callback=self.callback, ) tqm.run(play) finally: if tqm is not None: tqm.cleanup() if self.loader: self.loader.cleanup_all_tmp_files() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
def run(self, module, args=''): play_source = dict(name='Ansible Play', hosts=self.host_list, gather_facts='no', tasks=[dict(action=dict(module=module, args=args))]) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None callback = ResultsCollector(self.jobid) try: tqm = TaskQueueManager(inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords) tqm._stdout_callback = callback result = tqm.run(play) finally: if tqm is not None: tqm.cleanup() return callback.result
def runansible(self, host_list, task_list): play_source = dict(name="Ansible play", hosts=host_list, gather_facts='no', tasks=task_list) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) tqm = None try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, passwords=self.passwords, stdout_callback=self.results_callback, run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS, run_tree=False, ) result = tqm.run(play) finally: if tqm is not None: tqm.cleanup() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True) results_raw = {} results_raw['success'] = {} results_raw['failed'] = {} results_raw['unreacheable'] = {} for host, result in self.results_callback.host_ok.items(): results_raw['success'][host] = json.dumps(result._result) for host, result in self.results_callback.host_failed.items(): results_raw['failed'][host] = result._result['msg'] for host, result in self.results_callback.host_unreachable.items(): results_raw['unreachable'][host] = result._result['msg'] return results_raw
def run(self, host_list, module_name, module_args=None): """ 从 andible ad-hoc 运行模块. module_name: ansible 模块名称 (-m) module_args: ansible 模块参数 (-a) """ # 创建任务 play_source = dict( name="JK Play", hosts=host_list, gather_facts='no', tasks=[dict(action=dict(module=module_name, args=module_args))]) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) # 实际运行 # TaskQueueManager 是创建进程池, 负责输出结果和多进程间数据结构或者队列的共享协作 tqm = None # 结果回调类实例化 self.callback = ResultsCollector() try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, options=self.options, passwords=self.passwords, stdout_callback=self.callback, ) tqm.run(play) finally: if tqm is not None: tqm.cleanup() if self.loader: self.loader.cleanup_all_tmp_files() shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
def run(self, pattern, tasks, gather_facts='no'): """ ansible adhoc 模式运行任务 host_list: host 列表文件或者带逗号字符 :param pattern: :param tasks: :param gather_facts: :return: """ tasks = self.load_tasks(tasks) # tasks = [dict(action=dict(module='setup'))] # print(tasks) # create play with tasks play_source = dict(name="Ansible adhoc", hosts=pattern, gather_facts=gather_facts, tasks=tasks) play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) # actually run it tqm = None try: tqm = TaskQueueManager( inventory=self.inventory, variable_manager=self.variable_manager, loader=self.loader, passwords=self.passwords, stdout_callback=self.callback, ) # tqm._stdout_callback = self.callback tqm.run(play) # print(self.callback.d) finally: if tqm is not None: tqm.cleanup()
def run_adhoc(): variable_manager.extra_vars = { "ansible_ssh_user": "******" } #, "ansible_ssh_pass":"******"} # 增加外部变量 # 构建pb, 这里很有意思, 新版本运行ad-hoc或playbook都需要构建这样的pb, 只是最后调用play的类不一样 # :param name: 任务名,类似playbook中tasks中的name # :param hosts: playbook中的hosts # :param tasks: playbook中的tasks, 其实这就是playbook的语法, 因为tasks的值是个列表,因此可以写入多个task play_source = { "name": "Ansible Ad-Hoc", "hosts": "redis-server", "gather_facts": "no", "tasks": [{ "action": { "module": "shell", "args": "ls />>/a.txt" } }] } play = Play().load(play_source, variable_manager=variable_manager, loader=loader) tqm = None try: tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=None, stdout_callback='minimal', run_tree=False, ) result = tqm.run(play) print result finally: if tqm is not None: tqm.cleanup()