from ansible.cli.playbook import PlaybookCLI
from ansible.plugins.callback import CallbackBase
import json
from ansible.cli import CLI
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible import config
from ansible import constants as C
from ansible.playbook.play_context import PlayContext
import ansible
class ResultCallback(CallbackBase):
"""A sample callback plugin used for performing an action as results come in
If you want to collect all results into a single object for processing at
the end of the execution, look into utilizing the ``json`` callback plugin
or writing your own custom callback plugin
"""
def v2_runner_on_ok(self, result, **kwargs):
"""Print a json representation of the result
This method could store the result in an instance attribute for retrieval later
"""
host = result._host
print(json.dumps({host.name: result._result}, indent=4))
def v2_runner_on_failed(self, result, **kwargs):
host = result._host.get_name()
self.runner_on_failed(host, result._result, False)
print('===v2_runner_on_failed====host=%s===result=%s'%(host,result._result))
def v2_runner_on_unreachable(self, result):
host = result._host.get_name()
self.runner_on_unreachable(host, result._result)
print('===v2_runner_on_unreachable====host=%s===result=%s'%(host,result._result))
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',{})))
print("this task does not execute,please check parameter or condition.")
def v2_playbook_on_stats(self, stats):
print ("changed:%s" %stats.changed)
print ("ok:%s" %stats.ok)
print ("processed:%s" %stats.processed)
print ("failures:%s" %stats.failures)
print ("skipped:%s" %stats.skipped)
print('===========play executes completed========')
# Ansible Inventory实际上是包含静态Inventory和动态Inventory两部分,静态Inventory指的是在文件/etc/ansible/hosts中指定的主机和组,Dynamic Inventory指通过外部脚本获取主机列表,并按照ansible 所要求的格式返回给ansilbe命令的。
# 静态inventory
# cli = PlaybookCLI([" ","-i","/root/mtest/inventory.ini","-e", "@/etc/openstack_deploy/user_secrets.yml","-e", "@/etc/openstack_deploy/user_variables.yml", '/root/mtest/test.yml'])
# 动态inventory
cli = PlaybookCLI([" ","-i","/opt/openstack-ansible/inventory/dynamic_inventory.py","-e", "@/etc/openstack_deploy/user_secrets.yml","-e", "@/etc/openstack_deploy/user_variables.yml", '/root/mtest/test.yml'])
cli.parse()
super(PlaybookCLI,cli).run()
loader, inventory, variable_manager = cli._play_prereqs(cli.options)
# CLI.get_host_list(inventory, )
# CLI.get_host_list(inventory, cli.args)
# playbooks, inventory, variable_manager, loader, options, passwords
pbex = PlaybookExecutor(playbooks=cli.args, inventory=inventory,
variable_manager=variable_manager, loader=loader,options=cli.options,
passwords=None)
pbex._tqm._stdout_callback = ResultCallback()
result = pbex.run()
python ansible api
最新推荐文章于 2022-06-15 10:27:34 发布