Ansible中内含很多可用的模块,用playbook熟练运用这些模块其实就可以完成日常绝大部分任务。
但是其实由于其开源属性,Ansible有开放很多自定义编程的接口,方便大家用自己熟悉的语言进行更高级的自定义控制。
其中常用的Python、Bash脚本都可以完成自定义模块的编写。今天主要描述的Python场景下的自定义模块编写实例。
1、自定义模块的源文件需要放在什么位置?
Ansible会在放置Playbook脚本的根目录的library文件夹寻找自定义模块,如果根目录没有这个文件,麻烦新建。
2、先放上全部的源代码:
#!/usr/bin/python
def can_reach(module,host,port,timeout): //自定义模块实际操作函数体
nc_path = module.get_bin_path('nc', required=True) //注意:远程主机必须安装nc命令,否则报错
args = [nc_path,"-z","-w",str(timeout),host,str(port)]
(rc,stdout,stderr) = module.run_command(args) //通过run_command命令运行Linux命令
return rc==0
def main(): //自定义模块主体函数
module= AnsibleModule(
argument_spec = dict( //通过argument_spec获取Ansible传参
host=dict(required=True),
port=dict(required=True,type='int'),
timeout=dict(required=False,type='int',default=3)
),
supports_check_mode=True //开启检测模式
)
host=module.params['host']
port=module.params['port']
timeout=module.params['timeout']
if can_reach(module,host,port,timeout):
module.exit_json(changed=False)
else:
msg="Could not reach %s:%s"%(host,port)
module.fail_json(msg=msg)
from ansible.module_utils.basic import *
main()
3、在Playbook根目录创建一个playbook脚本,有一个范例可以参考(test_can-reach.yml):
---
- name: test can_reach
hosts: note note2
tasks:
- name: test
can_reach: host=www.baidu.com port=80
4、在Playbook根目录输入命令:ansible-playbook test_can-reach.yml