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')
)