|
#!/usr/bin/env python
# coding=utf-8
import json
import logging
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.plugins.callback import CallbackBase
from collections import namedtuple
from ansible import constants as C
import ansible.executor.task_result
import multiprocessing
>
def v2_runner_on_ok(self, result):
host = result._host
logging.warning('===v2_runner_on_ok====host=%s===result=%s' % (host, result._result))
def v2_runner_on_failed(self, result, ignore_errors=False):
host = result._host
logging.warning('===v2_runner_on_failed====host=%s===result=%s' % (host, result._result))
def v2_runner_on_unreachable(self, result):
host = result._host
logging.warning('===v2_runner_on_unreachable====host=%s===result=%s' % (host, result._result))
>
def __init__(self, hostlist, playbooks, *args, **kwargs):
self.hostlist = hostlist
self.playbooks = playbooks
self.passwords = None
self.callback = None
Options = namedtuple('Options', ['connection', 'remote_user', 'ask_sudo_pass', 'verbosity', 'ack_pass',
'module_path', 'forks', 'become', 'become_method', 'become_user',
'check', 'listhosts', 'listtasks', 'listtags', 'syntax',
'sudo_user', 'sudo', 'display_skipped_hosts'])
self.options = Options(connection='smart', remote_user='root', ack_pass=None, sudo_user='root',
forks=200, sudo='yes', ask_sudo_pass=False, verbosity=5, module_path=None,
become=True, become_method='su', become_user='root', check=None, listhosts=False,
listtasks=False, listtags=None, syntax=None, display_skipped_hosts=False)
self.loader = DataLoader()
self.variable_manager = VariableManager()
self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager,
host_list=self.hostlist)
self.variable_manager.set_inventory(self.inventory)
self.variable_manager.extra_vars = {"ansible_ssh_user": "root"} # 额外参数,包括playbook参数 key:value
def runplaybook(self):
playbook = PlaybookExecutor(
playbooks=self.playbooks,
inventory=self.inventory,
variable_manager=self.variable_manager,
loader=self.loader,
options=self.options,
passwords=None)
playbook._tqm._stdout_callback = ResultsCollector()
playbook.run()
if __name__ == '__main__':
#创建对象
anl = AnsibleAPI(['10.26.222.216'], ['/root/ansibleInventory_cl/df.yml'])
an2 = AnsibleAPI(['10.26.222.210', '10.26.222.213'], ['/root/ansibleInventory_cl/ifconfig.yml'])
#多进程
processes = []
p1 = multiprocessing.Process(name='process_one', target=anl.runplaybook)
p2 = multiprocessing.Process(name='process_two', target=an2.runplaybook)
processes.append(p1)
processes.append(p2)
for p in processes:
p.start()
print('tasks completed') |
|