黑技術: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')
)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章