模块执行流程
简要了解模块执行流程
1.将模块文件读入内存,然后添加传递给模块的参数,最后将模块中所需要的类添加到内存,由zipfile压缩后,再由base64进行编码,写入到模板文件内。
2.通过默认的连接方式(一般是ssh) , ansible连接到远程主机,创建临时目录,并关闭连接。
3.打开另外一个ssh连接,将模板文件以sftp方式传送到刚刚创建的临时目录中,写完后关闭连接。
4.打开一个ssh连接将任务对象赋予可执行权限,执行成功后关闭连接。
5.最后,ansible将再打开一个新连接来执行模块,并删除临时目录及其所有内容。
6.模块的结果是从标准输出stdout中获取json格式的字符串。ansible将解析和处理此字符串。
安装ansible
pip install ansible
模块库目录
可以使用ANSIBLE_LIBRARY环境变量来指定模块的存放位置,也可以在playbook当前目录下创建library目录。
mkdir /opt/library
export ANSIBLE_LIBRARY=/opt/library
案例:编写一个将远程机器文件目录移动位置的模块
#coding:utf-8
#导入要使用的模块
#编写ansible模块要继承AnsibleModule类
from ansible.module_utils.basic import AnsibleModule
import shutil
def main():
#使用AnsibleModule类中的argument_spec来接收参数
module = AnsibleModule(
argument_spec=dict(
old_file=dict(required=True, type='str'), #required=True 代表参数必须提供
new_file=dict(required=True, type='str')
)
)
#使用 shutil.copy拷贝文件
shutil.copy(module.params['old_file'], module.params['new_file'])
#拷贝完成后返回JSON数据
module.exit_json(changed=True)
if __name__ == '__main__':
main()
将 编写好的文件复制到ANSIBLE_LIBRARY环境目录下
[root@localhost ]# cp rcopy.py /opt/library/
[root@localhost ]# ls /opt/library/
rcopy.py
执行命令
[root@localhost ansible]# ansible 192.168.0.87 -m rcopy -a "old_file=/etc/hosts new_file=/tmp/myhosts.txt"
192.168.0.87 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true
}
注:yum安装的ansible会产生这种错误
[root@localhost ansible]# ansible 192.168.0.87 -m rcopy -a "old_file=/etc/hosts new_file=/tmp/myhosts.txt"
192.168.0.87 | FAILED! => {
"msg": "The module rcopy was not found in configured module paths"
}