模块是一个独立的, 可以复用的脚本, 它可以被anisible API, Ansible 或者ansible-playbook使用.   在模块退出之前, 它通过输出一个json字符串到标准输出从而反馈信息给ansible.  你可以用任何一种语言去写一个模块. 写好的模块可以放在ANSIBLE_LIBRARY或者--module-path目录下. 通常情况下playbook的目录下的library目录也可以做为模块的默认目录.

1. 模块的基本开发模式

  一个简单的模块, 之所以用这个作为例子, 是因为你可以用任何语言去开发自己的模块, 我们需要了解模块最基本的开发模式

#!/usr/bin/python

import datetime
import json date = str(datetime.datetime.now())
print json.dumps({
"time" : date
})

  模块测试

git clone git://github.com/ansible/ansible.git --recursive
source ansible/hacking/env-setup ansible/hacking/test-module -m ./timetest.py

  模块参数

  ansible会自动的把参数保存到一个参数文件中, 所以我们必须读取并分析这个文件. 这个参数文件只是一个字符串, 所以任何形式的参数都是合法的.

#!/usr/bin/python

# import some python modules that we'll use.  These are all
# available in Python's core import datetime
import sys
import json
import os
import shlex # read the argument string from the arguments file
args_file = sys.argv[1]
args_data = file(args_file).read() arguments = shlex.split(args_data)
for arg in arguments: # ignore any arguments without an equals in it
if "=" in arg: (key, value) = arg.split("=")
if key == "time": rc = os.system("date -s \"%s\"" % value) if rc != 0:
print json.dumps({
"failed" : True,
"msg" : "failed setting the time"
})
sys.exit(1) date = str(datetime.datetime.now())
print json.dumps({
"time" : date,
"changed" : True
})
sys.exit(0) date = str(datetime.datetime.now())
print json.dumps({
"time" : date
})
测试模块
ansible/hacking/test-module -m ./timetest.py -a "time=\"March 14 12:23\""

  二进制模块

  二进制模块的支持会在ansible2.2中加入,  当ansible发现是二进制模块是, 它会提供一个json文件argv[1]来保存参数.

  提供facts的模块

  setup模块可以提供很多系统相关的变量, 然而用户不修改系统模块也可以添加自定义变量, 只需要在模块的返回值中加入ansible_facts这个键值. 例如:

{
"changed" : True,
"rc" : 5,
"ansible_facts" : {
"leptons" : 5000,
"colors" : {
"red" : "FF0000",
"white" : "FFFFFF"
}
}
} 开发一个site_facts的模块并且在所有的playbook之前调用是一个较好的习惯,

2. 通用的模块样板

  如果你使用python来开发自定义模块, ansible提供了很多强大的快捷方式. 模块仍然保存在一个文件当中, 但是我们不需要再去处理参数文件. 最好的学习方法是去学习ansible的核心模块.

from ansible.module_utils.basic import AnsibleModule
if __name__ == '__main__':
main() Note: 对于ansible2.1来说, 上面的导入已经不能工作, 必须使用from ansible.module_utils.basic import *
def main():
module = AnsibleModule(
argument_spec = dict(
state = dict(default='present', choices=['present', 'absent']),
name = dict(required=True),
enabled = dict(required=True, type='bool'),
something = dict(aliases=['whatever'])
)
)
AnsibleModule 提供和很多通用的函数来处理返回值, 分析参数并允许你检查输入
成功返回
module.exit_json(changed=True, something_else=12345)
失败退出
module.fail_json(msg="Something fatal happened")

还有很多其他的基础功能, 课参看lib/ansible/module_utils/basic.py 

  check模式

  模块支持check模式. 如果用户在check模式下运行ansible, 模块会去尝试预判change是否发生. 如果想定义一个check模块, 用户必须在初始化模块的时候设置supports_check_mode=True

module = AnsibleModule(
argument_spec = dict(...),
supports_check_mode=True
) if module.check_mode:
# Check if any changes would be made but don't actually make those changes
module.exit_json(changed=check_if_system_state_would_be_changed())
作为模块的开发者, 你有责任去保证在check模式下没有系统状态被改变?
Remember that, as module developer, you are responsible for ensuring that no system state is altered when the user enables check mode. 如果你的模块不支持check模式, 而用户却在check模式下运行ansible, 你的模块会被自动跳过

  在模块中永远不要使用"print "some status message"".  因为在ansible中输出被假定为一个可用的json.

  Modules must not output anything on standard error, because the system will merge standard out with standard error and prevent the JSON from parsing. Capturing standard error and returning it as a variable in the JSON on standard out is fine, and is, in fact, how the command module is implemented.

ANSIBLE_KEEP_REMOTE_FILES 这个参数会保留在远程服务器上执行的python脚本. 可以用来debug.

ansible module的更多相关文章

  1. Ansible详解(一)

    简介 Ansible是一个简单的自动化运维管理工具,基于Python语言实现,由Paramiko和PyYAML两个关键模块构建,可用于自动化部署应用.配置.编排task(持续交付.无宕机更新等).主版 ...

  2. ansible配置文件详解

    # ansible配置文件配置 配置项介绍 , 配置文件ansible.cfg, 运行playbook时,默认时在yaml文件所在路径寻找,然后再去/etc/ansible/下寻找 [defaults ...

  3. Ansible安装部署以及常用模块详解

    一.  Ansible 介绍Ansible是一个配置管理系统configuration management system, python 语言是运维人员必须会的语言, ansible 是一个基于py ...

  4. 初探ansible

    Ansible 基于ssh的自动化运维工具 ansible 配置文件详解 ansible.cfg 文件 文件默认放置在/etc/ansible下,ansible读取配置文件的顺序是: 当前命令执行目录 ...

  5. ansible环境部署及常用模块总结 - 运维笔记

    一.  Ansible 介绍Ansible是一个配置管理系统configuration management system, python 语言是运维人员必须会的语言, ansible 是一个基于py ...

  6. 【Ansible】的python api

    [Ansible API] Ansible本身就是由python写成,所有其对python形式的API的支持应该不错. 其API分不同的版本,这个版本也就是ansible本身的版本,可以通过ansib ...

  7. 1、Ansible简介及简单安装、使用

    参考Ansible权威指南:https://ansible-tran.readthedocs.io/en/latest/index.html 以下内容学习自马哥教育 Ansible: 运维工作:系统安 ...

  8. 【Ansible 文档】【译文】网络支持

    Networking Support 网络支持 Working with Networking Devices 使用网络设备 自从Ansible 2.1开始,你现在可以使用成熟模型 - 编写 play ...

  9. 【Ansible 文档】【译文】Windows 支持

    see also:List of Windows Modules Windows Support Windows 支持 Windows: How Does It Work Windows:如何工作 正 ...

随机推荐

  1. Dump Checking

    Dump Checking Debug相关的一些小技巧 摘要: 1. 如何Debug一个进程的子进程? 答: 使用WinDBG attach到父进程, 然后输入命令".childdbg 1& ...

  2. HTTP状态码的意义

    100系列码 从100到199范围的HTTP状态码是信息报告码.基于各种原因考虑,大多数情况下我们是 很少看见这些代码的.首先,如果一个浏览器尝试访问一个网站,而网站返回这些代码时,它们往往都不会显示 ...

  3. Ping其他电脑ping不通的解决方法

    要想Ping通其他电脑,首先要看被PING的电脑,是否允许PING. 一.在被PING电脑操作系统为XP下分为:1.被PING 电脑关闭了防火墙,就完全可以PING通:2.被PING 电脑开了防火墙, ...

  4. LigerUI权限系统之角色管理

    角色管理比前面几个页面都稍显复杂点.好吧,还是先看图. 左边是角色列表,右边是页面列表,它们也是多对多的关系,即一个角色可以访问多个页面,同时一个页面也可以被多个角色访问. 点击左边的角色,刷新右边页 ...

  5. 下载centos6.4

    下载centos6.4 (原创)LAMP教程3-下载centos6.4 今天我要给大家讲的是安装CentOS-6.4-x86_64,是的没有错,就是64位的,因为我的机子是4G的内存,安装64位的ce ...

  6. DB2使用存储过程插入数据

    要求:插入一张表(TESTMV)中三个字段(ID, GROUPID[组id], USERID[用户id]),为了产生多个组,每个组多个人的数据,进行统计每个组多少人数据用 代码如下: delete t ...

  7. Standford机器学习 聚类算法(clustering)和非监督学习(unsupervised Learning)

    聚类算法是一类非监督学习算法,在有监督学习中,学习的目标是要在两类样本中找出他们的分界,训练数据是给定标签的,要么属于正类要么属于负类.而非监督学习,它的目的是在一个没有标签的数据集中找出这个数据集的 ...

  8. VS2012下基于Glut 矩阵变换示例程序2:

    在VS2012下基于Glut 矩阵变换示例程序:中我们在绘制甜圈或者圆柱时使用矩阵对相应的坐标进行变换后自己绘制甜圈或者圆柱.我们也可以使用glLoadMatrixf.glLoadMatrixd载入变 ...

  9. Hexo站点之域名配置

    摘要 因为Hexo个人博客是托管在github之上,每次访问都要使用githubname.github.io这么一个长串的域名来访问,会显得非常繁琐.这个时候我们可以购买一个域名,设置DNS跳转,以达 ...

  10. Android 关于ListView中按钮监听的优化问题(方法一)

    在Android应用开发过程中经常会用到ListView,并且每次在item中都要对点击事件进行监听.在给按钮添加OnClickListener时,一般会下意识的在getView()中找到每一个But ...