黑技术:python开发ansible自定义模块

Ansible有很多常用模块

  • 1、ping模块
  • 2、raw模块
  • 3、yum模块
  • 4、apt模块
  • 5、pip模块
  • 6、synchronize模块
  • 7、template模块
  • 8、copy模块
  • 9、user 模块与group模块
  • 10、service 模块
  • 11、get_url 模块
  • 12、fetch模块
  • 13、file模块
  • 14、unarchive模块
  • 15、command 模块和shell

我们可以很方便的批量在目标主机执行远程操作

但是如何开发自己的模块呢?
比如我们要实现一个功能,控制远程多台服务器下载mysql安装包
我们可以自己开发一个模块remote_copy(当然不用自己开发的模块也可以)

开始自定义模块开发

在library目录下,新建文件remote_copy.py

#!/usr/bin/python env
# coding:utf-8


def do_copy(module, file, dest):
    try:
        new_file = dest + '/' + os.path.basename(file)
        mkdir(dest)
        f = urllib2.urlopen(file)
        data = f.read()
        f = open(new_file, 'wb')
        f.write(data)
        f.close()
    except BaseException:
        return False
    else:
        return True



def mkdir(path):
    # 引入模块
    import os

    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")

    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)

    # 判断结果
    if not isExists:
        os.makedirs(path)
        return True
    else:
        # 如果目录存在则不创建,并提示目录已存在
        return False


def main():
    module = AnsibleModule(
        argument_spec=dict(
            file=dict(required=True, type='str'),
            dest=dict(required=True, type='str'),
        ),
        supports_check_mode=True,
    )
    print(module)
    if module.check_mode:
        module.exit_json(changed=False)

    file = module.params['file']
    dest = module.params['dest']

    if do_copy(module, file, dest):
        module.exit_json(changed=True)
    else:
        msg = file + dest
        module.fail_json(msg=msg)


from ansible.module_utils.basic import *
import shutil
import os
import urllib2
from ansible.inventory.manager import InventoryManager
if __name__ == '__main__':
    main()


# ---
#
# - name: test remote_copy module
#   hosts: webserver01
#   gather_facts: false
#
#   tasks:
#     - name: do a remote host
#       remote_copy: file=https://raw.githubusercontent.com/kubernetes/dashboard/v1.10.1/src/deploy/recommended/kubernetes-dashboard.yaml dest=/etc/wpp2


现在就可以直接使用了~

playbook.yaml

---
- hosts: myserver
  tasks:
    - name: do a remote host
      remote_copy: file=https://www.mysql.com/mysql.rpm dest=/etc/mysql

ps:

文件头部加入下列语句,表示该模块使用python运行

#!/usr/bin/python
#

创建模块的入口,并使用AnsibleModule类中的argument_spec来接受参数

module = AnsibleModule(
    argument_spec = dict(
    source=dict(required=True, type='str'),
    dest=dict(required=True, type='str')
)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值