一 模块说明

  • 官方是否有提供的类似功能模块?
    可从下面两个连接确定官方提供的模块,以免重复造轮子
    官方已发布的模块 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. yii2使用 db log

    在本地测试的时候,输出log,还是输出到db中比较顺手. 配置过程: 1.加入log组件的配置: 'log' =>[ # 追踪级别 # 消息跟踪级别 # 在开发的时候,通常希望看到每个日志消息来 ...

  2. akka消息传递

    消息传递 消息本身要求是什么?是否必须可以序列化?消息传递根据传递的要求严格程序依次分为三类,1.至多一次到达 至消息最多一次传递到目的端,消息可能会丢失,但不会重复2.至少一次到达 潜在可能存在多次 ...

  3. 【android】开发笔记---存储篇

    SQLite批量插入数据 当我们执行 db.execSQL("sql语句")的时候,系统进行了一次IO操作,当批量插入成千上万条时,就会消耗掉许多资源. 解决之道是通过事务,统一提 ...

  4. 【npm】使用淘宝提供的镜像来加速npm

    国外的npm用着非常不稳定,时常一直就卡在安装的进度条上 淘宝提供了一个国内镜像,保障了安装网络环境的稳定,和源地址10分钟同步一次,没有被收录的包会自动切换到npm官方下载,并添加进镜像库. 地址: ...

  5. Spark高级数据分析· 6LSA

    潜在语义分析 wget http://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles-multistream.xml.bz ...

  6. 利用C++调用天气webservice-gSOAP方法

    首先需要下载一个gSOAP工具包 下载路径为:https://sourceforge.NET/projects/gsoap2/ 至于有关于gSOAP的一些用法和包含的文件的说明可从官网查看:http: ...

  7. c++第三十二天

    p164~p170: 大致内容 迭代语句 1.while语句. 2.传统for. 3.范围for.两个注意点是:1- 通常使用auto来确保类型相容,2- 如果需要修改元素则需要使用&符(还可 ...

  8. js 图表处理之Echar

    官网学习链接:http://echarts.baidu.com/tutorial.html#5%20分钟上手%20ECharts 案例代码: <!DOCTYPE html> <htm ...

  9. 20145314郑凯杰《信息安全系统设计基础》第6周学习总结 part A

    第4章 处理器体系结构 part 1 本部分对改章节的知识点进行总结: 一个处理器支持的指令和指令的字节级编码称为它的指令集体系结构(ISA). 不同的出路器有不同的ISA. ISA模型看上去应该是顺 ...

  10. java语言基本环境搭建

    从放假开始,就开始路陆陆续续了解关于java语言的学习.首先从语言编辑环境就和以前学习的c语言会有些不同,对java语言的学习也有了很大很多新的认识. 首先从官网上下载jdk,按照娄老师给我们的操作提 ...