from collections import namedtuple
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.inventory import Inventory
from ansible.parsing.dataloader import DataLoader
from ansible.plugins.callback import CallbackBase
from ansible.vars import VariableManager
class AnsibleTaskResultCallback(CallbackBase):
def __init__(self, display=None, option=None):
super().__init__(display, option)
self.result = None
self.error_msg = None
def v2_runner_on_ok(self, result):
res = getattr(result, ‘_result‘)
self.result = res
self.error_msg = res.get(‘stderr‘)
def v2_runner_on_failed(self, result, ignore_errors=None):
if ignore_errors:
return
res = getattr(result, ‘_result‘)
self.error_msg = res.get(‘stderr‘, ‘‘) + res.get(‘msg‘)
def runner_on_unreachable(self, host, result):
if result.get(‘unreachable‘):
self.error_msg = host + ‘:‘ + result.get(‘msg‘, ‘‘)
def v2_runner_item_on_failed(self, result):
res = getattr(result, ‘_result‘)
self.error_msg = res.get(‘stderr‘, ‘‘) + res.get(‘msg‘)
def run_playbook(ssh_user, sudo_user,playbook_path, playbook_extra_vars):
loader = DataLoader()
variable_manager = VariableManager() # 管理添加变量
# /etc/ansible/hosts
inventory = Inventory(
loader=loader,
variable_manager=variable_manager,
host_list=‘/ansible/hosts‘)
variable_manager.set_inventory(inventory)
playbooks = []
if playbook_path is not None:
playbooks.append(playbook_path)
if playbook_extra_vars is not None:
variable_manager.extra_vars = playbook_extra_vars
Options = namedtuple(
‘Options‘, [
‘listtags‘,
‘listtasks‘,
‘listhosts‘,
‘syntax‘,
‘connection‘,
‘module_path‘,
‘forks‘,
‘remote_user‘,
‘private_key_file‘,
‘ssh_common_args‘,
‘ssh_extra_args‘,
‘sftp_extra_args‘,
‘scp_extra_args‘,
‘become‘,
‘become_method‘,
‘become_user‘,
‘verbosity‘,
‘check‘])
options = Options(
listtags=False,
listtasks=False,
listhosts=False,
syntax=False,
connection=‘ssh‘,
module_path=None,
forks=100,
remote_user=ssh_user,
private_key_file=None,
ssh_common_args=None,
ssh_extra_args=None,
sftp_extra_args=None,
scp_extra_args=None,
become=True,
become_method=None,
become_user=sudo_user,
verbosity=None,
check=False)
playbook_executor = PlaybookExecutor(
playbooks=playbooks,
inventory=inventory,
variable_manager=variable_manager,
loader=loader,#负责yaml和json的加载
options=options)
result_callback = AnsibleTaskResultCallback()
playbook_executor._tqm._stdout_callback = result_callback
result = playbook_executor.run()