一 模块说明

  • 官方是否有提供的类似功能模块?
    可从下面两个连接确定官方提供的模块,以免重复造轮子
    官方已发布的模块 http://docs.ansible.com/ansible/modules.html
    官方正在开发的模块 https://github.com/ansible/ansible/labels/module
  • 你需要开发一个action 插件么?
    action插件是在ansible主机上运行,而不是在目标主机上运行的。对于类似file/copy/template功能的模块,在模块执行前需要在ansible主机上做一些操作的。
- 模块是传送到目标主机上运行的。
- 模块的返回值必须是json dumps的字符串。

 

1 模块执行的过程

首先,将模块文件读入内存,然后添加传递给模块的参数,最后将模块中所需要的类添加到内存,由zipfile压缩后,再由base64进行编码,写入到模版文件内。

通过默认的连接方式,一般是ssh。ansible通过ssh连接到远程主机,创建临时目录,并关闭连接。然后将打开另外一个ssh连接,将模版文件以sftp方式传送到刚刚创建的临时目录中,写完后关闭连接。然后打开一个ssh连接将任务对象赋予可执行权限,执行成功后关闭连接。

最后,ansible将打开第三个连接来执行模块,并删除临时目录及其所有内容。模块的结果是从标准输出stdout中获取json格式的字符串。ansible将解析和处理此字符串。如果有任务是异步控制执行的,ansible将在模块完成之前关闭第三个连接,并且返回主机后,在规定的时间内检查任务状态,直到模块完成或规定的时间超时。

 

使用了管道连接后,与远程主机只有一个连接,命令通过数据流的方式发送执行。

配置方式

vim /etc/ansible/ansible.cfg
pipelining = True

  

执行过程

Ansible提供了许多模块实用程序,它们提供了在开发自己的模块时可以使用的辅助功能。 basic.py模块为程序提供访问Ansible库的主要入口点,所有Ansible模块必须至少从basic.py导入:

 from ansible.module_utils.basic import *

其他模块工具

a10.py - Utilities used by the a10_server module to manage A10 Networks devices.
api.py - Adds shared support for generic API modules.
aos.py - Module support utilities for managing Apstra AOS Server.
asa.py - Module support utilities for managing Cisco ASA network devices.
azure_rm_common.py - Definitions and utilities for Microsoft Azure Resource Manager template deployments.
basic.py - General definitions and helper utilities for Ansible modules.
cloudstack.py - Utilities for CloudStack modules.
database.py - Miscellaneous helper functions for PostGRES and MySQL
docker_common.py - Definitions and helper utilities for modules working with Docker.
ec2.py - Definitions and utilities for modules working with Amazon EC2
eos.py - Helper functions for modules working with EOS networking devices.
f5.py - Helper functions for modules working with F5 networking devices.
facts.py - Helper functions for modules that return facts.
gce.py - Definitions and helper functions for modules that work with Google Compute Engine resources.
ios.py - Definitions and helper functions for modules that manage Cisco IOS networking devices
iosxr.py - Definitions and helper functions for modules that manage Cisco IOS-XR networking devices
ismount.py - Contains single helper function that fixes os.path.ismount
junos.py - Definitions and helper functions for modules that manage Junos networking devices
known_hosts.py - utilities for working with known_hosts file
mysql.py - Allows modules to connect to a MySQL instance
netapp.py - Functions and utilities for modules that work with the NetApp storage platforms.
netcfg.py - Configuration utility functions for use by networking modules
netcmd.py - Defines commands and comparison operators for use in networking modules
network.py - Functions for running commands on networking devices
nxos.py - Contains definitions and helper functions specific to Cisco NXOS networking devices
openstack.py - Utilities for modules that work with Openstack instances.
openswitch.py - Definitions and helper functions for modules that manage OpenSwitch devices
powershell.ps1 - Utilities for working with Microsoft Windows clients
pycompat24.py - Exception workaround for Python 2.4.
rax.py - Definitions and helper functions for modules that work with Rackspace resources.
redhat.py - Functions for modules that manage Red Hat Network registration and subscriptions
service.py - Contains utilities to enable modules to work with Linux services (placeholder, not in use).
shell.py - Functions to allow modules to create shells and work with shell commands
six/init.py - Bundled copy of the Six Python library to aid in writing code compatible with both Python 2 and Python 3.
splitter.py - String splitting and manipulation utilities for working with Jinja2 templates
urls.py - Utilities for working with http and https requests
vca.py - Contains utilities for modules that work with VMware vCloud Air
vmware.py - Contains utilities for modules that work with VMware vSphere VMs
vyos.py - Definitions and functions for working with VyOS networking

  

二 构建一个简单的模块

1 基本步骤

1) 创建目录

将这个模块放在library目录下,命名为remote_reach.py
可以使用 ANSIBLE_LIBRARY环境变量来指定模块的存放位置。也可以在playbook当前目录下创建library目录

2) 创建模块

#!/usr/bin/python env
# coding:utf-8 def can_reach(module,host):
ping_path = module.get_bin_path('ping', required=True)
args = [ping_path, '-c 4',host]
(rc,stdout,stderr) = module.run_command(args) return rc == 0 def main():
module = AnsibleModule(
argument_spec=dict(
host = dict(required=True,type='str'),
),
supports_check_mode=True,
) if module.check_mode:
module.exit_json(changed=False) host = module.params['host'] if can_reach(module,host):
module.exit_json(changed=True)
else:
msg = 'Could not reach %s' %(host)
module.fail_json(msg=msg) from ansible.module_utils.basic import * if __name__ == '__main__':
main()

3) 编写yaml文件使用模块 

编写yaml文件使用这个模块

---

- name: test remote_copy module
hosts: webserver01
gather_facts: false tasks:
- name: do a remote host
remote_copy: host=172.20.1.100

4) 测试模块 

可以使用test-module.py 进行模块测试

5) 执行这个yaml文件

ansible-playbook remote_copy.yml   # 执行这个yaml

  

2 module提供facts数据

与作为模块退出的一部分返回的数据类似,模块也可以直接创建fact数据,通过名为ansible_facts键返回数据到主机。无需为任务register一个变量来获取数值。

remote_facts = {'rc_source': module.params['source'], 'rc_dest': module.params['dest'] } 
module.exit_json(changed=True, ansible_facts=remote_facts)

在playbook中添加查看fact的任务

- name: show a fact
debug: var=rc_dest

  

3 检查模式

模块可以选择支持检查模式http://docs.ansible.com/ansible/playbooks_checkmode.html。 如果用户在检查模式下运行可执行安全性,则模块应该尝试预测和报告是否发生更改,但实际上不会进行任何更改(不支持检查模式的模块也不会采取任何动作,但只是不会报告其可能的更改)。

对于您的模块支持检查模式,您必须在实例化AnsibleModule对象时传递supports_check_mode = True。 当启用检查模式时,AnsibleModule.check_mode属性将计算为True。 例如:

module = AnsibleModule( argument_spec = dict( source=dict(required=True, type='path'), dest=dict(required=True, type='path') ), supports_check_mode=True ) 

if not module.check_mode:
shutil.copy(module.params['source'], module.params['dest'])

在进行检查模式的时候,不执行拷贝动作,看下列运行状态。

 ansible-playbook remote_copy.yml -C

三 添加module文档说明

所有模块必须按以下顺序定义以下部分:

  1. ANSIBLE_METADATA
  2. DOCUMENTATION
  3. EXAMPLES
  4. RETURNS
  5. Python imports

1. 定义ANSIBLE_METADATA,该变量描述有关其他工具使用的模块的信息

ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}

2. 定义DOCUMENTATION,该变量描述模块的描述信息,参数,作者和许可信息。

DOCUMENTATION = '''
--- module: remote_copy
version_added: "2.3"
short_description: Copy a file on the remote host
description:
- The remote_copy module copies a file on the remote host from a given source to a provided destination. options:
source:
description:
- Path to a file on the source file on the remote host
required: true
dest:
description:
- Path to the destination on the remote host for the copy
required: true
author:
- "Lework" '''

  

3. 定义EXAMPLES,该变量用来描述模块的一个或多个示例使用

EXAMPLES = ''' 

# Example from Ansible Playbooks 

- name: backup a config file
remote_copy:
    source: /etc/herp/derp.conf
    dest: /root/herp-derp.conf.bak '''

  

4. 定义RETURN,该变量用来描述模块的返回数据信息

添加参数source和dest返回信息

module.exit_json(changed=True, source=module.params['source'], dest=module.params['dest'])

定义RETURN

RETURN = ''' source: description: source file used for the copy returned: success type: string sample: "/path/to/file.name" dest: description: destination of the copy returned: success type: string sample: "/path/to/destination.file" gid: description: group id of the file, after execution returned: success type: int sample: 100 group: description: group of the file, after execution returned: success type: string sample: "httpd" owner: description: owner of the file, after execution returned: success type: string sample: "httpd" uid: description: owner id of the file, after execution returned: success type: int sample: 100 mode: description: permissions of the target, after execution returned: success type: string sample: "0644" size: description: size of the target, after execution returned: success type: int sample: 1220 state: description: state of the target, after execution returned: success type: string sample: "file" '''

  

字符串的格式为yaml格式。

可以通过ansible-doc 来查看这些信息

ansible-doc -M library remote_copy

  

用于格式化字符串的一些选项,用于DOCUMENTATION

|函数| 描述 |例子|
|:---|:---|
|U() |格式化url |Required if I(state=present)|
|I() |格式化选项名称 |Mutually exclusive with I(project_src) and I(files)|
|M() |格式化模块名称 |See also M(win_copy) or M(win_template).|
|C() |格式化文件和选项值 |Or if not set the environment variable C(ACME_PASSWORD) will be used.|

  

Documentation 加载外部的文档

某些类别的模块有共同的文档信息,就可以使用docs_fragments共享出来。
所有的docs_fragments都可以在lib/ansible/utils/module_docs_fragments/ 目录下找到

在Documentation 字符串中添加下列字段,就可以添加外部的文档信息

extends_documentation_fragment:
- files
- validate

ansible modules开发(一)的更多相关文章

  1. ansible modules开发(二)

    四 使用其他语言发开module cd /etc/ansible cat library/touch.sh #!/bin/sh args_file=$1 [ ! -f "$args_file ...

  2. 074——VUE中vuex之模块化modules开发实例

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. [系统开发] 基于Ansible的产品上线系统

    前言: 应部门急需,开发了一套基于Ansible Playbook的产品上线系统.由于时间很紧,UI直接套用了之前开发的一套perl cgi模板,后续计划用 django 重新编写. 个人感觉该系统的 ...

  4. 如何在Mac系统里面更新 Ansible 的 Extra Modules

    最近遇到一个问题 seport is not a legal parameter in an Ansible task or handler 原因是我本地 Ansible 的 Extra Module ...

  5. Ansible playbook API 开发 调用测试

    Ansible是Agentless的轻量级批量配置管理工具,由于出现的比较晚(13年)基于Ansible进行开发的相关文档较少,因此,这里通过一些小的实验,结合现有资料以及源码,探索一下Ansible ...

  6. Ansible 开发调试 之【模块调试】

    本地调试 需要安装jinja2 库 yum -y install python-jinja2 使用官方提供的测试脚本调试 git clone git://github.com/ansible/ansi ...

  7. windows下使用pycharm开发基于ansible api的python程序

    Window下python安装ansible,基于ansible api开发python程序 在windows下使用pycharm开发基于ansible api的python程序时,发现ansible ...

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

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

  9. ansible服务部署与使用

    第1章 ssh+key实现基于密钥连接(ansible使用前提) 说明:    ansible其功能实现基于SSH远程连接服务    使用ansible需要首先实现ssh密钥连接 1.1 部署ssh ...

随机推荐

  1. nfs 安装及使用

    安装 引用: https://zerlong.com/537.html Windows Server2012搭建NFS服务器 2017-06-01 5739 Views 1153 Times 开启NF ...

  2. PKU 2823 Sliding Window(线段树||RMQ||单调队列)

    题目大意:原题链接(定长区间求最值) 给定长为n的数组,求出每k个数之间的最小/大值. 解法一:线段树 segtree节点存储区间的最小/大值 Query_min(int p,int l,int r, ...

  3. Jenkins系统+独立部署系统

    原文出自:http://os.51cto.com/art/201601/504846.htm 有了Jenkins,为什么还需要一个独立的部署系统? 现在已经有Jenkins,它自身提供了丰富的部署插件 ...

  4. 最值得阅读学习的 10 个 C 语言开源项目代码

    1. Webbench Webbench是一个在linux下使用的非常简单的网站压测工具.它使用fork()模拟多个客户端同时访问我们设定的URL,测试网站在压力下工作的性能,最多可以模拟3万个并发连 ...

  5. Pythonic 的代码编写方法

    1.模块导入 你是不是经常对调用模块时输入一长串模块索引感到头疼?说实在的,数量少的时候或许还可以勉强忍受,一旦程序规模上去了,这也是一项不容小觑的工程 #Bad import urllib.requ ...

  6. 在Ubuntu中启动./jmeter-server报错Server failed to start: java.rmi.RemoteException: Cannot start. ranxf is a loopback address.解决方法

      执行失败错误信息: root@ranxf:/home/ranxf/apache-jmeter-3.1/bin# ./jmeter-server Writing log file to: /home ...

  7. C++MFC之picture control控件铺满图片

    UpdateData(true); //更新路径公共变量     CString m_path = m_edit1.GetString();      if(m_path=="") ...

  8. 【Beginning Python】抽象(未完)

    [懒惰即是美德] 抽象意味着良好的可读性:说明你在努力做什么,而不是给出你正在如何做的细节. [抽象和结构] 程序应该是非常抽象的,就像“下载网页.计算频率.打印每个单词的频率”一样易懂.翻译成程序就 ...

  9. DNSmasq安装配置

    dns安装配置yum -y install dnsmasq dns配置文件vi /etc/dnsmasq.confresolv-file=/etc/resolv.dnsmasq.confaddn-ho ...

  10. 20145324 《Java程序设计》第9周学习总结

    20145324 <Java程序设计>第9周学习总结 教材学习内容总结 第十六章 1.JDBC是java联机数据库的标准规范.它定义了一组标准类与接口,标准API中的接口会有数据库厂商操作 ...