ansible playbook API得到任务执行返回结果

1. ansisble2.x playbook api与ansible1.9.x的相差很大,而且直观看来配置复杂多了
2.以下案例是通过loggin打印出来ansible模块执行结果,如若需要得到,可以加入中间件,如rabbitmq,将消息publish出去,另一处消费该消息即可


(1) ansible1.9.x playbook api
#!/usr/bin/env python
# coding=utf-8
import ansible.runner
import logging
from ansible.playbook import PlayBook
from ansible.inventory import Inventory
from ansible import callbacks
from ansible import utils
from ansible import callbacks


class PlaybookRunnerCallbacks(callbacks.PlaybookRunnerCallbacks):

    def __init__(self, stats, verbose=None):
        super(PlaybookRunnerCallbacks, self).__init__(stats, verbose)

    def on_ok(self, host, host_result):
        super(PlaybookRunnerCallbacks, self).on_ok(host, host_result)
        logging.warning('===on_ok====host=%s===result=%s'%(host,host_result))

    def on_unreachable(self, host, results):
        super(PlaybookRunnerCallbacks, self).on_unreachable(host, results)
        logging.warning('===on_unreachable====host=%s===result=%s'%(host,results))

    def on_failed(self, host, results, ignore_errors=False):
        super(PlaybookRunnerCallbacks, self).on_failed(host, results, ignore_errors)
        logging.warning('===on_unreachable====host=%s===result=%s'%(host,results))

    def on_skipped(self, host, item=None):
        super(PlaybookRunnerCallbacks, self).on_skipped(host, item)
        logging.warning("this task does not execute,please check parameter or condition.")

class PlaybookCallbacks(callbacks.PlaybookCallbacks):

    def __init__(self,verbose=False):
        super(PlaybookCallbacks, self).__init__(verbose)

    def on_stats(self, stats):
        super(PlaybookCallbacks, self).on_stats( stats)
        logging.warning("palybook executes completed====")

hosts = ['127.0.0.1', '192.168.234.3']
inventory = Inventory(hosts)
stats = callbacks.AggregateStats()
runner_cb = PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
playbook_cb = PlaybookCallbacks()
res=ansible.playbook.PlayBook(
    playbook='/tmp/playbook.yaml',
    stats=stats,
    callbacks=playbook_cb,
    runner_callbacks=runner_cb,
    inventory=inventory,
    forks=200
)
result = res.run()
playbook_cb.on_stats(res.stats)


2. ansible2 playbook api
#!/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


class ResultsCollector(CallbackBase):

    def __init__(self,*args, **kwargs):
        super(ResultsCollector, self).__init__(*args, **kwargs)

    def _get_return_data(self, result):
        try:
            if result.get('msg',None):
                return_data= result.get('msg')
            elif result.get('stderr',None):
                return_data= result.get('stderr')
            else:
                return_data = result
        except:
            pass
        return return_data.encode('utf-8')

    def v2_runner_on_ok(self, result):
      host = result._host.get_name()
      self.runner_on_ok(host, result._result)
      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.get_name()
      self.runner_on_failed(host, result._result, ignore_errors)
      return_data = self._get_return_data(result._result)
      logging.warning('===v2_runner_on_failed====host=%s===result=%s'%(host,return_data))

    def v2_runner_on_unreachable(self, result):
      host = result._host.get_name()
      self.runner_on_unreachable(host, result._result)
      return_data = self._get_return_data(result._result)
      logging.warning('===v2_runner_on_unreachable====host=%s===result=%s'%(host,return_data))

    def v2_runner_on_skipped(self, result):
        if C.DISPLAY_SKIPPED_HOSTS:
         host = result._host.get_name()
         self.runner_on_skipped(host, self._get_item(getattr(result._result,'results',{})))
         logging.warning("this task does not execute,please check parameter or condition.")

    def v2_playbook_on_stats(self, stats):
      logging.warning('===========palybook executes completed========')

loader = DataLoader()
variable_manager = VariableManager()
inventory = Inventory(loader = loader, variable_manager = variable_manager, host_list = ['127.0.0.1', '192.168.234.3'])
variable_manager.set_inventory(inventory)
variable_manager.extra_vars={"ansible_ssh_user":"root"} #额外参数,包括playbook参数 key:value

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'])

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=None,
            listtasks=None,
            listtags=None,
            syntax=None)

playbook = PlaybookExecutor(playbooks=['/tmp/playbook.yaml'],
                  inventory=inventory,
                  variable_manager=variable_manager,
                  loader=loader,
                  options=options,
                  passwords=None)
playbook._tqm._stdout_callback = ResultsCollector()
res = playbook.run()

你可能感兴趣的:(ansible)