官方文档见  http://docs.ansible.com/ansible/dev_guide/developing_api.html

拿官方的例子修改如下

import json
from collections import namedtuple
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.task_result import TaskResult
from ansible.plugins.callback import CallbackBase # 自定义 callback,即在运行 api 后调用本类中的 v2_runner_on_ok(),在这里会输出 host 和 result 格式
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
"""
# result 包含'_check_key', '_host', '_result', '_task', 'is_changed', 'is_failed', 'is_skipped', 'is_unreachable'
host = result._host
print json.dumps({host.name: result._result}, indent=4) """
def v2_on_any(self, *args, **kwargs):
if isinstance(args[0], TaskResult):
print json.dumps({args[0]._host.name: args[0]._result}, indent=4)
""" Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check'])
# initialize needed objects
variable_manager = VariableManager()
loader = DataLoader()
options = Options(connection='smart', module_path=None, forks=100, become=None, become_method=None, become_user=None, check=False)
passwords = dict(conn_pass='mypassword') # 目前只发现有两个key,conn_pass, become_pass # Instantiate our ResultCallback for handling results as they come in
results_callback = ResultCallback() # create inventory and pass to var manager
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list='hosts')
# hosts文件,也可以是 ip列表 '10.1.162.18:322, 10.1.167.36' 或者 ['10.1.162.18:322', '10.1.167.36']
variable_manager.set_inventory(inventory) # create play with tasks
play_source = dict(
name = "Ansible Play",
hosts = 'web', # 对应 playbook 入口yaml文件的 hosts变量,也可以是 ip 10.1.162.18
gather_facts = 'no',
tasks = [
dict(action=dict(module='shell', args='ifconfig'), register='shell_out'),
#dict(action=dict(module='debug', args=dict(msg='{{shell_out.stdout}}')))
]
)
play = Play().load(play_source, variable_manager=variable_manager, loader=loader) # actually run it
# TaskQueueManager 是创建进程池,负责输出结果和多进程间数据结构或者队列的共享协作
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
stdout_callback=results_callback, # Use our custom callback instead of the ``default`` callback plugin
# 如果注释掉 callback 则会调用原生的 DEFAULT_STDOUT_CALLBACK,输出 task result的output,同 ansible-playbook debug
)
result = tqm.run(play)
print result # 返回码,只要有一个 host 出错就会返回 非0 数字
finally:
if tqm is not None:
tqm.cleanup()

如果需要统一输出可以重写

v2_runner_on_failed(self, result, ignore_errors=False)
v2_runner_on_ok(self, result)
v2_runner_on_skipped(self, result)
v2_runner_on_unreachable(self, result)
v2_runner_on_no_hosts(self, task)
具体可以参考 plugins/callback/__init__.py

ansible-playbook api 2.0 直接运行的更多相关文章

  1. Ansible playbook API 开发 调用测试

    Ansible是Agentless的轻量级批量配置管理工具,由于出现的比较晚(13年)基于Ansible进行开发的相关文档较少,因此,这里通过一些小的实验,结合现有资料以及源码,探索一下Ansible ...

  2. ansible-playbook api 2.0 运行项目

    上篇 api 的文章 <ansible-playbook api 2.0 直接运行> 介绍的是直接将 tasks 直接写在 代码中的,本文介绍 api 运行整个项目 [root@10_1_ ...

  3. ansible 调用playbook api执行(一)

    一 调用ansible playbook api执行playbook 1 准备好hosts文件 root@ansible:~/ansible/playbooks# cat hosts [all:var ...

  4. Python+Django+ansible playbook自动化运维项目实战☝☝☝

    Python+Django+ansible playbook自动化运维项目实战☝☝☝  一.入门引导 DevOPSDevOps(英文Development和Operations的组合)是一组过程.方法 ...

  5. ansible playbook实践(四)-如何调试写好的playbook文件

    有时,我们写了一个长长,功能很强悍的yaml文件,但是,我们有可能会担心,写的yaml文件是否正确,是否有漏洞危机,毕竟是要修改线上的机器,那么,有可能我们可以从以下几个检查维度来进行,确保在大规模应 ...

  6. ansible笔记(11):初识ansible playbook(二)

    ansible笔记():初识ansible playbook(二) 有前文作为基础,如下示例是非常容易理解的: --- - hosts: test211 remote_user: root tasks ...

  7. python调用ansible接口API执行命令

    python版本:Python 2.6.6 ansible版本:ansible 2.3.1.0      下载地址:https://releases.ansible.com/ansible/ 调用脚本 ...

  8. ansible入门四(Ansible playbook基础组件介绍)

    本节内容: ansible playbook介绍 ansible playbook基础组件 playbook中使用变量 一.ansible playbook介绍 playbook是由一个或多个“pla ...

  9. ansible - playbook(剧组)

    目录 ansible - playbook(剧组) 常用命令 五种传参方式 常用元素详解 tags handlers template when 循环 嵌套循环 ansible - playbook( ...

随机推荐

  1. varnish--vcl

    ●Varnish Configuration Language - VCL(varnish配置语言-VCL)          Varnish有一个很棒的配置系统,大部分其他的系统使用配置指令,让您打 ...

  2. git仓库搬家

    1). 从原地址克隆一份裸版本库 git clone --bare git://xxxxx.com/xxx.git 2). 然后到新的 Git 服务器上创建一个新项目 3). 以镜像推送的方式上传代码 ...

  3. collections之deque【双向队列】与Queue【单向队列】

    今天来向大家介绍两个队列,一个是deque,双向队列,另外一个是Queue,单向队列,队列和堆栈不同,队列为先进先出,大家还需要注意一下,双向队列为collections模块中的类,而Queue为qu ...

  4. iOS 基于MVC设计模式的基类设计

    iOS 基于MVC设计模式的基类设计 https://www.jianshu.com/p/3b580ffdae00

  5. 基本控件设置边角图片 drawableleft

    btn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_galley_comment, 0, 0,0); 四个参数分别是左上右下四个方向 ...

  6. IntentService----意图服务

    意图服务是异步进行的  执行完操作后就会自己消毁(onDestroy方法) 本例为点击按钮下载三张图片相当于连续执行三次意图服务中的onStartcommand方法 import android.ap ...

  7. win 下 nginx 与 php的配置

    1.下载需要的软件包 php的windows版本(*注意这里下载非线程安全的,nginx使用的是cgi) http://windows.php.net/download/   nginx的window ...

  8. git 常用命令笔记

    #提交代码会加上用户名和邮箱 git config --global user.name 名字 git config --global user.email 邮箱 git config --globa ...

  9. Spring框架的IOC核心功能快速入门

    2. 步骤一:下载Spring框架的开发包 * 官网:http://spring.io/ * 下载地址:http://repo.springsource.org/libs-release-local/ ...

  10. Java中 Random

    Java中的Random()函数 (2013-01-24 21:01:04) 转载▼ 标签: java random 随机函数 杂谈 分类: Java 今天在做Java练习的时候注意到了Java里面的 ...