ansible api挪用

时间:2022-04-24 07:55:27

标签:ansible api挪用

例子: #!/usr/bin/python import json from collections import namedtuple from ansible.parsing.dataloader import DataLoader from ansible.vars.manager import VariableManager from ansible.inventory.manager import InventoryManager from ansible.playbook.play import Play from ansible.executor.task_queue_manager import TaskQueueManager from ansible.executor.task_result import TaskResult from ansible.plugins.callback import CallbackBase class ResultCallback(CallbackBase): def v2_runner_on_ok(self, result, **kwargs): host = result._host print(json.dumps({host.name: result._result}, indent=4)) Options = namedtuple(‘Options‘, [‘connection‘, ‘module_path‘, ‘forks‘, ‘become‘, ‘become_method‘, ‘become_user‘, ‘check‘, ‘diff‘]) loader = DataLoader() options = Options(connection=‘smart‘, module_path=None, forks=2, become=None, become_method=None, become_user=None, check=False, diff=False) #connection参数,如果执行本地节点用‘local‘, 远端节点用‘smart‘ #passwords = dict(vault_pass=‘xxxxx‘)    #密钥方法打消这步 results_callback = ResultCallback() inventory = InventoryManager(loader=loader, sources=[‘hosts‘]) variable_manager = VariableManager(loader=loader, inventory=inventory) #variable_manager.set_inventory(inventory) play_source = dict( name = "Ansible Play", hosts = ‘webserver‘, gather_facts = ‘no‘, tasks = [ dict(action=dict(module=‘shell‘, args=‘df -Th‘), 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=None, stdout_callback=results_callback, ) result = tqm.run(play) print(result) finally: if tqm is not None: tqm.cleanup()