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 ...
随机推荐
- LibreOJ 6282. 数列分块入门 6
题目链接:https://loj.ac/problem/6282 参考博客:http://www.cnblogs.com/stxy-ferryman/p/8560551.html 这里如果用数组的话元 ...
- Shell教程 之函数
1.函数定义 shell中函数的定义格式如下: [ function ] funname [()] { action; [return int;] } 说明: 可以带function fun() 定义 ...
- 100-days: Five
Title: Feel better now ? The rise and rise of the anxiety economy(焦虑经济) rise and rise 一直上升 anxiety n ...
- 转)VCSA 6.5重启无法访问,报错“503 Service Unavailable”的解决方法
1. 问题 重启vcenter,登陆vsphere client,提示 “503 Service Unavailable (Failed to connect to endpoint: [N7Vmac ...
- FortiGate基本信息
1.介绍 FortiGate是全新的下一代防火墙,在整个硬件架构和系统上面都有新的设计,在性能和功能上面都有了很大提升,具有性能高.接口丰富.功能齐全.安全路由交换一体化.性价比高等优势. Forti ...
- 项目总结01:JSP mysql SpringMvc下中国省市县三级联动下拉框
JSP mysql SpringMvc下中国省市县三级联动下拉框 关键词 JSP mysql数据库 SpringMvc ajax Controller层 Service层 中国地区 省 ...
- 【centos】centos中添加一个新用户,并授权
前言 有时候给root用户不太方便,新建一个用于并赋予权限这个做法相对好些 创建新用户 创建一个用户名为:cmj [root@localhost ~]# adduser cmj 为这个用户初始化密码, ...
- 【环境配置】本地配置sublime text以及和远程linux设置sftp
工具: sublime text 2(mac版) 远程linux(centos 7系) securCRT(for mac) [本地安装并配置securCRT(for mac)] 关于配置: 1.解决终 ...
- 纯css背景图自适应
只需要这样设置即可,只要你的图片足够大的话可以无限缩小,当不在缩小的时候则跟你的实际图片大小有关系
- MVC的Forms登录验证
第一步:修改web.config配置 在 <system.web>节点下加入配置:未登录的用户跳转到/Home/Login,登录后跳转到/Home/UserCenter,登录后票证记录到c ...