python学习之ansible api
Python API 2.0
从2.0的事情开始更复杂一些,但是你会得到更多离散和可读的类:
#!/usr/bin/env python 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.plugins.callback import CallbackBase class ResultCallback(CallbackBase):
"""用于执行结果的示例回调插件 如果要将所有结果收集到单个对象进行处理
执行的结束,看看利用``json``回调插件
或编写自己的自定义回调插件
"""
def v2_runner_on_ok(self, result, **kwargs):
"""打印结果的json表示 该方法可以将结果存储在实例属性中以供以后检索
"""
host = result._host
print json.dumps({host.name: result._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='local', module_path='/path/to/mymodules', forks=100, become=None, become_method=None, become_user=None, check=False)
passwords = dict(vault_pass='secret') #实例化我们的ResultCallback来处理结果进来时
results_callback = ResultCallback() #创建库存并传递给var manager
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list='localhost')
variable_manager.set_inventory(inventory) # create play with tasks
play_source = dict(
name = "Ansible Play",
hosts = 'localhost',
gather_facts = 'no',
tasks = [
dict(action=dict(module='shell', args='ls'), 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
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
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
Python API pre 2.0
这很简单:
import ansible.runner runner = ansible.runner.Runner(
module_name='ping',
module_args='',
pattern='web*',
forks=10
)
datastructure = runner.run()
运行方法返回每个主机的结果,根据是否可以联系来分组。 返回类型是模块特定的,如关于模块文档中所示:
{
"dark" : {
"web1.example.com" : "failure message"
},
"contacted" : {
"web2.example.com" : 1
}
}
一个模块可以返回任何类型的JSON数据,所以Ansible可以作为框架来快速构建强大的应用程序和脚本。
详细API示例
以下脚本打印出所有主机的正常运行时间信息:
#!/usr/bin/python import ansible.runner
import sys # construct the ansible runner and execute on all hosts
results = ansible.runner.Runner(
pattern='*', forks=10,
module_name='command', module_args='/usr/bin/uptime',
).run() if results is None:
print "No hosts found"
sys.exit(1) print "UP ***********"
for (hostname, result) in results['contacted'].items():
if not 'failed' in result:
print "%s >>> %s" % (hostname, result['stdout']) print "FAILED *******"
for (hostname, result) in results['contacted'].items():
if 'failed' in result:
print "%s >>> %s" % (hostname, result['msg']) print "DOWN *********"
for (hostname, result) in results['dark'].items():
print "%s >>> %s" % (hostname, result)
高级程序员也可能希望将源读取到ansible本身,因为它使用API(具有所有可用选项)来实现可执行的命令行工具(lib / ansible / cli /)。
更多信息请参考官网:http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html
python学习之ansible api的更多相关文章
- Python调用ansible API系列(五)综合使用
如何把动态生成资产信息.执行playbook以及自定义结果结合起来用呢? #!/usr/bin/env python # -*- coding: utf-8 -*- """ ...
- Python调用ansible API系列(四)动态生成hosts文件
方法一:通过最原始的操作文件的方式 #!/usr/bin/env python # -*- coding: utf-8 -*- """ 通过操作文件形式动态生成ansib ...
- windows下使用pycharm开发基于ansible api的python程序
Window下python安装ansible,基于ansible api开发python程序 在windows下使用pycharm开发基于ansible api的python程序时,发现ansible ...
- ansible Api 2.3-2.4
官网示例(python3) 说明: 在学习2.0 api的过程中遇到了一个坑,最新版的ansible(2.4)和2.3版本api引用时发生了变化,本文主要使用2.3 api进行操作,2.4只做分析 a ...
- Python之路【第二十四篇】:Python学习路径及练手项目合集
Python学习路径及练手项目合集 Wayne Shi· 2 个月前 参照:https://zhuanlan.zhihu.com/p/23561159 更多文章欢迎关注专栏:学习编程. 本系列Py ...
- Python学习计划
---恢复内容开始--- Python学习计划 https://edu.csdn.net/topic/python2?utm_source=blog4 匠人之心,成就真正Python全栈工程师 ...
- python学习博客地址集合。。。
python学习博客地址集合... 老师讲课博客目录 http://www.bootcdn.cn/bootstrap/ bootstrap cdn在线地址 http://www.cnblogs. ...
- python学习笔记(二)、字符串操作
该一系列python学习笔记都是根据<Python基础教程(第3版)>内容所记录整理的 1.字符串基本操作 所有标准序列操作(索引.切片.乘法.成员资格检查.长度.最小值和最大值)都适用于 ...
- Deep learning with Python 学习笔记(8)
Keras 函数式编程 利用 Keras 函数式 API,你可以构建类图(graph-like)模型.在不同的输入之间共享某一层,并且还可以像使用 Python 函数一样使用 Keras 模型.Ker ...
随机推荐
- TZOJ 3315 买火车票(线段树区间最小值)
描述 Byteotian州铁道部决定赶上时代,为此他们引进了城市联网.假设城市联网顺次连接着n 个市从1 到n 编号(起始城市编号为1,终止城市编号为n).每辆火车有m个座位且在任何两个运送更多的乘客 ...
- [LeetCode_105]Construct Binary Tree from Preorder and Inorder Traversal
题目链接 https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ 题意 由二叉 ...
- SQLServer BI 学习笔记
MSBI 学习库: https://ask.hellobi.com/blog/biwork SSAS库部署的几种方式 http://www.cnblogs.com/aspnetx/archive/20 ...
- elasticsearch查询语句总结
query 和 filter 的区别请看:https://www.cnblogs.com/bainianminguo/articles/10396956.html Filter DSL term 过 ...
- jquery实现元素高度变化页面变化
试了几种方法包括有资料说的h5新特性,都没能满足我的需求.我的需求如下: 元素高度是动态可变的,比如可拖动teatarea元素 最后用到了指针监听事件解决了 @参考文档 $(document).mou ...
- echarts折线图Demo
echarts链接:http://echarts.baidu.com/examples/editor.html?c=line-stack 黑底代码:http://gallery.echartsjs.c ...
- idea不识别yml配置文件,怎么办?
问题描述: 如下图,新建的springboot项目,添加了自定义的配置文件后,2.yml无法像上方文件的一样,被识别成配置文件! 虽然可能不会影响项目(不确定),但问题不解决,根本没有心情开始下一 ...
- 489. Robot Room Cleaner扫地机器人
[抄题]: Given a robot cleaner in a room modeled as a grid. Each cell in the grid can be empty or block ...
- 842. Split Array into Fibonacci Sequence能否把数列返回成斐波那契数列
[抄题]: Given a string S of digits, such as S = "123456579", we can split it into a Fibonacc ...
- IOS开发之无法选择模拟器显示NO Scheme
1. 不是 文件冲突的 看这个链接https://blog.csdn.net/sanpintian/article/details/7377365 2.文件冲突的 打开工程文件. 打开 直接 搜索 ...