ansible模块开发

模块执行流程

简要了解模块执行流程 

        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"
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值