如果没有书面授权,请勿转载

第五章 自己定义模块

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样板代码为有效地编写模块。

终于。我们写了一个脚本,让你清点库存报价从外部文件。

Ansible@一个有效的配置管理工具--Ansible configure management--翻译(十二)的更多相关文章

  1. Ansible@一个高效的配置管理工具--Ansible configure management--翻译(一)

    未经书面许可,请勿转载 ---      Ansible is the simplest way to automate apps and IT infrastructure 这是Ansible官方站 ...

  2. Ansible@一个高效的配置管理工具--Ansible configure management--翻译(三)

    未经书面许可.请勿转载 一张图简单概括 Simple Playbooks Ansible is useful as a command-line tool for making small chang ...

  3. Ansible@一个高效的配置管理工具--Ansible configure management--翻译(五)

    无书面许可请勿转载 高级Playbook Extra variables You may have seen in our template example in the previous chapt ...

  4. Ansible@一个高效的配置管理工具--Ansible configure management--翻译(十一)

    无书面授权,请勿转载 第五章 自己定义模块 Using a module Now that we have written our very first module for Ansible, we ...

  5. Ansible@一个高效的配置管理工具--Ansible configure management--翻译(八)

    如无书面授权,请勿转载 第四章,大型项目中Ansible的使用 Roles If your playbooks start expanding beyond what includes can hel ...

  6. Ansible@一个有效的配置管理工具--Ansible configure management--翻译(四)

    不要未经书面许可转载 第三章是长,因为,我会分几个部分来翻译. Advanced Playbooks So far the playbooks that we have looked at are s ...

  7. Ansible@一个高效的配置管理工具--Ansible configure management--翻译(七)

    如无书面授权,请勿转载 Larger Projects Until now, we have been looking at single plays in one playbook file. Th ...

  8. Ansible@一个有效的配置管理工具--Ansible configure management--翻译(十)

    未经书面许可,.请勿转载 Custom Modules Until now we have been working solely with the tools provided to us by A ...

  9. Ansible 运维自动化 ( 配置管理工具 )

    背景 出差背景,要搞项目的自动化部署.因为只直接对接生产分发,机器又非常多,这样以往使用的bat只能作为应急方案了,还是得考虑使用专业化的工具来做这个事情! 当下有许多的运维自动化工具( 配置管理 ) ...

随机推荐

  1. android recover 系统代码分析 -- 选择进入

    最近做Recovery的规范及操作指导文档,花了一些时间将流程搞清. Android利用Recovery模式,进行恢复出厂设置,OTA升级,patch升级及firmware升级.而在进入Recover ...

  2. UVALive 4119 Always an integer (差分数列,模拟)

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud Always an integer Time Limit:3000MS     M ...

  3. Codeforces Round #277(Div 2) A、B、C、D、E题解

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud A. Calculating Function 水题,判个奇偶即可 #includ ...

  4. mysql中函数DISTINCT,group by,CONCAT及GROUP_CONCAT的使用

    一:DISTINCT 在使用mysql时,有时需要查询出某个字段不重复的记录,虽然mysql提供有distinct这个关键字来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是 ...

  5. zend framework 初识

    1. 请求顺序 : index.php --> Bootstrap.php --> IndexController.php 2. 验证顺序 : Bootstrap.php function ...

  6. 用Python写的简单脚本更新本地hosts

    这两天Google墙得严重,于是就产生了做个一键更新hosts的脚本的想法. 由于正在学习Python,理所当然用Python来写这个脚本了. 接触比较多的就是urllib2这个库,习惯性的impor ...

  7. 1008 Gnome Tetravex

    练习使用DPS的题,不知道有无别的做法,思路不复杂.形式是统计并且进行数字配对. #include <stdio.h> ][],note[],ans[]; void ini(){ int ...

  8. Eclipse 安装使用 Maven

    安装 Maven 下载 Maven  http://mirrors.hust.edu.cn/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9 ...

  9. 雅思创始人Keith Taylor谈英语学习

    雅思创始人Keith Taylor谈英语学习 “要学的是信息,而不是语言” 我们要学习一个国家的语言就得知道这个国家的方方面面.要学习英语就得了解英美国家的社会.经济.人文.历史等各方面的信息. 大家 ...

  10. 运行时数据区即内存分配管理——JVM之六

    内存分配结构,请参考: http://iamzhongyong.iteye.com/blog/1333100