设为首页 收藏本站
查看: 1518|回复: 0

[经验分享] Ansible@一个高效的配置管理工具--Ansible configure management--翻译(十二)

[复制链接]

尚未签到

发表于 2015-11-26 09:56:23 | 显示全部楼层 |阅读模式
如无书面授权,请勿转载

第五章 自定义模块
  External inventories
In the first chapter we saw how Ansible needs an inventory file, so that it knows
where its hosts are and how to access them. Ansible also allows you to specify a
script that allows you to fetch the inventory from another source. External
inventory scripts can be written in any language that you like as long as they
output valid JSON.
An external inventory script has to accept two different calls from Ansible. If called
with –list , it must return a list of all the available groups and the hosts in them.
Additionally, it may be called with --host . In this case, the second argument will be
a hostname and the script is expected to return a list of variables for that host. All the
outputs are expected in JSON, so you should use a language that supports it naturally.




外部库存设备清单
  第一章中介绍了Ansible的运行需要一个设备库存清单文件,让他可以知道需要访问那些主机设备。Ansible还可以通过脚本让你选择其他的库存清单文件,这个脚本可以可以用任何语言来写,只要他的输出格式符合JSON。
  


  外部库存清单的脚本需要接受2种Ansible的调用,如果用用--list调用,它返回一个可以用的组和主机列表;如果用--host调用,则返回一个可用的主机列表。所有的输出必须是JSON格式,所以你使用的语言最好能轻易的支持这座格式。
  Let's write a module that takes a CSV file listing all your machines and presents
this to Ansible as an inventory. This will be handy if you have a CMDB that allows
you to export your machine list as CSV, or for someone who keeps records of
their machines in Excel. Additionally, it doesn't require any dependencies outside
Python, as a CSV processing module is already included with Python. This really just
parses the CSV file into the right data structures and prints them out as JSON data
structures. The following is an example CSV file we wish to process; you may wish
to customize it for the machines in your environment:
Group,Host,Variables
test,example,ansible_ssh_user=root
test,localhost,connection=local
  让我们来写一个从包含你所有机器的CSV文件提取数据,然后发布到Ansible库存清单的模块。如果你有一个可以用来将设备导出到CSV的CMDB(数据库),或则设备记录被保存在一个excel表格里面,这个模块就很有用了。另外,它不需要任何python之外的依赖,它只需要解析CSV文件,然后把数据输出成JSON格式。下面是一个我们希望处理的CSV文件例子;你也可以自定义你自己环境中的机器:
  Group,Host,Variables

test,example,ansible_ssh_user=root

test,localhost,connection=local
  This file needs to be converted into two different JSON outputs. When --list is
called, we need to output the whole thing in a form that looks like this:
{"test": ["example", "localhost"]}
And when it is called with the arguments --host example , it should return this:
{"ansible_ssh_user": "root"}
Here is the script that opens a file named machines.csv and produces the dictionary
of the groups if --list is given. Additionally, when given --host and a hostname,
it parses that host's variables and returns them as a dictionary. The script is well-
commented, so you can see what it is doing. You can run the script manually with
the --list and --host arguments to confirm that it behaves correctly.

这个文件需要被转化成2种格式的JSON输出,当用--list调用的时候,像这样:
  {"test": ["example", "localhost"]}
  当用--host调用的时候,这样:
  {"ansible_ssh_user": "root"}
  下面的脚本例子打开一个叫machines.csv文件,当调用--list时候,它将组用字典来表示,当用--host调用的时候,它将主机和他们的变量用字典表示。脚本已经被很好的注释了。你可以使用--list和--host两个参数来测试:
  #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import csv
import json
def getlist(csvfile):
# Init local variables
#初始化本地变量
glist = dict()
rowcount = 0
# Iterate over all the rows
#历遍所有的行
for row in csvfile:
# Throw away the header (Row 0)
#去掉第一行,标题行
if rowcount != 0:
# Get the values out of the row
#获取非标题行的数据
(group, host, variables) = row
# If this is the first time we've
# read this group create an empty
# list for it
#如果第一次读这个组,则给他新建一个列表
if group not in glist:
glist[group] = list()
# Add the host to the list
#把主机加到这个列表中
glist[group].append(host)
# Count the rows we've processed
#计算我们已经处理的行
rowcount += 1
return glist
def gethost(csvfile, host):
# Init local variables
#初始化本地变量
rowcount = 0
# Iterate over all the rows
#历遍所有行
for row in csvfile:
# Throw away the header (Row 0)
#去掉标题行
if rowcount != 0 and row[1] == host:
# Get the values out of the row
#获取非标题行的数据
variables = dict()
for kvpair in row[2].split():
key, value = kvpair.split('=', 1)
variables[key] = value
return variables
# Count the rows we've processed
#计算我们已经处理的行数量
rowcount += 1
command = sys.argv[1]
#Open the CSV and start parsing it
#打开csv文件,开始处理
with open('machines.csv', 'r') as infile:
result = dict()
csvfile = csv.reader(infile)
if command == '--list':
result = getlist(csvfile)
elif command == '--host':
result = gethost(csvfile, sys.argv[2])
print json.dumps(result)


  


  You can now use this inventory script to provide the inventory when using Ansible.
A quick way to test that everything is working correctly is to use the ping module to
test the connection to all the machines. This command will not test whether the hosts
are in the right groups; if you want to do that, you can use the same ping module
command but instead of running it across all, you can simply use the group you
would like to test.
$ ansible -i csvinventory -m ping all

现在当你使用Anisbile的时候可以使用这个脚本提供库存清单列表了。使用ping模块来连接清单里所有的机器,来测试一下这个脚本是否运行良好。当主机不在他所在的组里时,会失败,不过你可以单独ping下试试。使用组来测试的命令如下:
  $ ansible -i csvinventory -m ping all
  Similar to when you used the ping module in Chapter 1, Getting Started with Ansible,
you should see an output that looks like the following:
localhost | success >> {
"changed": false,
"ping": "pong"
}
example | success >> {
"changed": false,
"ping": "pong"
}
This indicates that you can connect and use Ansible on all the hosts from your
inventory. You can use the same -i argument with ansible-playbook to run your
playbooks with the same inventory.跟第一章一样,输出类似下面这样:
  localhost | success >> {

"changed": false,

"ping": "pong"

}

example | success >> {

"changed": false,

"ping": "pong"

}


  

你可以连接清单里面所有的机器,也可以使用-i 参数来运行playbook。
  Summary
Having read this chapter you should now be able to build modules using either Bash
or any other languages that you know. You should be able to install modules that you
have either obtained from the Internet, or written yourself. We also covered how to
write modules more efficiently using the boilerplate code in Python. Finally, we wrote
an inventory script that allows you to pull your inventory from an external source.



本章小结
  读完本章后,你应该可以使用bash或则其他你会的语言来创建自定义模块,会安装你从互联网下载的模块,或则自己编写。我们还介绍了如何使用python的样板代码来有效的编写模块。最后,我们写了一个库存清单脚本可以让你从外部的文件中引用库存清单。


  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-143754-1-1.html 上篇帖子: Ansible@一个高效的配置管理工具--Ansible configure management--翻译(十一) 下篇帖子: ganglia监控自定义metric实践
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表