Ansible自定义模块
描述: 用户部署mondo客户端程序
具体代码见附件
执行脚本 : ansible zhangb_test2 -m mondo_deploy
参数说明:
zhangb_test2 :分组名称,即将一批主机按业务或其他标准进行分组,这里暂且将要装的主机IP划分到一个组里面。具体配置在/etc/ansible/hosts 文件中
-m :指明所用的模块(这里使用我们自定义的模块mondo_deploy)
-----------------------------------------------------------------------
#!/usr/bin/python
# -*- coding: utf-8 -*-
DOCUMENTATION = '''
---
module: mondo_deploy
short_description: check mondo client if has been deploy , if not exist then deploy.
description:
- check mondo client if has been deploy , if not exist then deploy.
version_added: "1.0"
notes:
- Not tested on any debian based system.
author: zhangb biao <xtayhame@189.cn>
'''
import urllib2
import os
import json
import hashlib
import time
import urllib
from time import sleep
import getpass
import subprocess
import commands
#op2(132)
#server1='http://132.121.97.178:9518/sync/'
#192
#server2='http://192.168.51.191:9518/sync/'
#172
#server3='http://172.20.3.219:9518/sync/'
server_links = ['http://132.121.97.178:9518/sync/',
'http://192.168.51.191:9518/sync/',
'http://172.20.3.219:9518/sync/',]
down_dir='/data/mondev/mondo/client/'
log_dir='/data/mondev/mondo/client/log/'
def getCurrentServer():
dict_server={}
print 'get current can connect server......'
for link in server_links:
try:
f = urllib2.urlopen(url=link,timeout=10)
if f is not None:
if f.code == 200:
now_server = link
server_json = f.read()
f.close()
dict_server['now_server'] = now_server
dict_server['server_json'] = server_json
break
except:
print ''
return dict_server
def createMulitDir(dir_path):
try:
if os.path.exists(dir_path) and os.path.isdir(dir_path):
pass
else:
os.makedirs(dir_path)
except:
return False
def download(remotepath, locapath, servimd5, tempfile=True):
time.sleep(1)
tempath = ''
if tempfile == True:
tempath = locapath + '.tmp'
urllib.urlretrieve(remotepath, tempath)
time.sleep(1)
if os.path.exists(tempath):
if getMd5(tempath) == servimd5:
try:
os.rename(tempath, locapath)
chmod(locapath)
except Exception, e:
return False
else:
return False
def chmod(filepath):
if os.path.isfile(filepath):
if filepath.endswith('.sh'):
os.system("chmod 744 %s" % (filepath))
elif filepath.endswith('.py'):
os.system("chmod 644 %s" % (filepath))
else:
os.system("chmod 744 %s" % (filepath))
'''
get file's MD5 value
'''
def getMd5(file_path):
with open(file_path,'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
return hash
'''
restart
'''
def restart():
try:
createMulitDir(log_dir)
p = subprocess.Popen(['sh','/data/mondev/mondo/client/bin/magent','restart'],stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
except Exception,ex:
return False
'''
update mondev user's crontab
'''
def updateCrontab():
file_name='/data/mondev/crontab_temp'
if os.path.exists(file_name) and os.path.isfile(file_name):
os.remove(file_name)
f = open(file_name,'a')
f.write('0 */24 * * * /data/mondev/mondo/client/bin/magent restart\n')
f.close()
if os.path.isfile(file_name):
tuple_temp = commands.getstatusoutput('crontab /data/mondev/crontab_temp')
if tuple_temp and tuple_temp[0] == 0:
return True
else:
return False
else:
return False
'''
check mondo client process if exist.
'''
def checkProcesss():
tuple_temp = commands.getstatusoutput('ps -ef|grep mondev|grep -v grep|grep magent|wc -l')
if tuple_temp and tuple_temp[0] == 0:
print 'tuple_temp[1]=',tuple_temp[1]
if tuple_temp[1] == '2':
return True
return False
def startDeploy():
dict_temp={}
dict_temp['result'] = False
username = getpass.getuser()
if username is not None and username == "mondev":
if checkProcesss():
dict_temp['result'] = True
dict_temp['msg'] = 'mondo client has benn deployed.'
else:
print 'begin to deploy monod project.'
dict_server = getCurrentServer()
if dict_server and len(dict_server) == 2:
now_server = dict_server['now_server']
server_json = dict_server['server_json']
print 'server link:', now_server
print 'server json:' , server_json
json_obj = json.loads(server_json)
if json_obj:
for ak , av in json_obj.items():
file_dir = os.path.dirname(ak)
file_name = os.path.basename(ak)
temp_dir=''
if file_dir is not None:
temp_dir = os.path.join(down_dir,file_dir)
else:
temp_dir = down_dir
if os.path.exists(temp_dir) and os.path.isdir(temp_dir):
pass
else:
createMulitDir(temp_dir)
file_path = os.path.join(temp_dir,file_name)
file_md5 = json_obj[ak]['md5']
if os.path.isfile(file_path):
md5 = getMd5(file_path)
if md5 is not None and file_md5 == md5:
pass
else:
download(os.path.join(now_server,ak), file_path, file_md5, tempfile=True)
else:
download(os.path.join(now_server,ak), file_path, file_md5, tempfile=True)
restart()
updateCrontab()
time.sleep(3)
if checkProcesss():
dict_temp['result'] = True
dict_temp['msg'] = 'deployed success.'
else:
dict_temp['msg'] = 'Error:deploy fail......'
else:
dict_temp['msg'] = "Error:service return result is not right......"
else:
dict_temp['msg'] = "Error:Can't find useful server link......"
else:
dict_temp['msg'] = 'Error:current user is not mondev......'
return dict_temp
def main():
module = AnsibleModule(
argument_spec = dict(),supports_check_mode=True
)
try:
dict_temp = startDeploy()
if dict_temp and dict_temp['result']:
module.exit_json(msg=dict_temp['msg'])
else:
module.exit_json(msg=dict_temp['msg'])
except Exception, ex:
module.fail_json(changed=False, msg='%s ' % ex)
from ansible.module_utils.basic import *
main()
----------------------------------------------------------------------
@dianxinguangchang.43F.zhongshanerlu.yuexiuqu.guangzhoushi.guangdongsheng
2016-11-03 17:20
分享到:
相关推荐
Ansible模块,用于在mysql表中设置值或插入记录。 对于将配置存储在数据库中的Web应用程序很有用。 例如,icingaweb2需要将初始用户插入数据库。 install-wizard可以做到,但是Ansible想要自动安装;) 在Ansible ...
Ansible-ansible-mysql-query.zip,ansible自定义模块,允许您在mysql databasesansible role:mysql\u query中设置值,ansible是一个简单而强大的自动化引擎。它用于帮助配置管理、应用程序部署和任务自动化。
Ansible模块:差异一些尚未由提交或接受的自定义ansible模块。用法Ansible模块,用于对字符串,文件和命令输出进行通用差异。争论名称必需的默认描述来源是的diff的源输入。 可以是字符串,文件内容或命令的输出,...
8. Ansible变量之自定义变量 9. Ansible变量之fact 10. Ansible魔法变量及变量优先级 11. 使用lookup生成变量 12. Ansible Vault配置加密 13. Ansible文件管理模块及Jinja2过滤器 14. Ansible Playbook with_X循环...
Ansible-ansible-modules.zip,自定义可扩展模块可扩展模块,ansible是一个简单而强大的自动化引擎。它用于帮助配置管理、应用程序部署和任务自动化。
ansible是新出现的自动化运维工具,基于...(3)、各种模块核心模块、command模块、自定义模块; (4)、借助于插件完成记录日志邮件等功能; (5)、playbook:剧本执行多个任务时,非必需可以让节点一次性运行多个任务
Ansible塔的定制Webhook 该项目的主要目的是为与Ansible Tower一起使用的自定义Webhook提供自动化的Ansible安装程序。 该webhook可以与GitHub结合使用(计划在以后添加更多提供商),以允许Git中的webhooks在提交/推...
选择您将保存自定义ansible模块的位置 mkdir ~/custom-ansible-modules cd ~/custom-ansible-modules 克隆此存储库 git clone git@github.com:DistilledLtd/ansible-linode-nodebalancer.git 将新模块符号链接到...
用于自动Oracle修补的Ansible模块和手册 概要 作者:伊维卡·阿尔索夫(Ivica Arsov) 联系人: : 上一个模块版本:2.0.1 最近更新:23.12.2019 Python版本 随着对Python 2的支持即将结束(2019年底),Orapatch...
ansible ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署... 各种模块核心模块、command模块、自定义模块;
转自 Linux轻量级自动运维工具-Ansible浅析 – ~微风~ – 51CTO技术博客 ...支持自定义模块,使用任意编程语言; 强大的playbook机制; 幂等性; 安装及程序环境: 程序: ansible ansible-playbook ansible
支持自定义模块支持playbook:可以把多个任务编排好,一次性的执行完。幂等性:多次执行的结果是一样的。ansible命令的使用方式还是很简单的:host_pattern是来指定主机的,可以是单台主机,也可以是主机组。前提是...
如何通常,为了让 Ansible 扫描您的自定义插件目录(并加载实现类),您应该在活动ansible.cfg文件的defaults部分中提供正确的路径。 另请参阅上。 例如,如果您将此存储库检出到主项目根文件夹下的ansible_plugins...
深入了解Ansible的工作原理使用加密数据完全自动化Ansible剧本的执行访问和操作剧本中的变量数据使用块执行故障恢复或清除探索Playbook调试器和Ansible控制台有效地排除意外行为与云基础架构提供商和容器系统合作...
只有自定义代码存储在站点存储库中。 存储库和节点模块被缓存在工作空间中,以加快后续部署的速度。 入门 安装然后运行以下命令: # Clone this repository. git clone git@github....
Ansible训练有关如何使用Ansible的概述大纲什么是Ansible Ansible组件Ansible配置文件管理库存管理变量掌握YAML 使用Ansible模块管理Ansible剧本了解角色复杂的剧本创建自定义Ansible模块使用Ansible Galaxy 测试...
您将学习如何创建和安装自定义模块和插件,这些模块和插件可以集成在一起以使流程自动化以加快软件交付速度。您将学到什么使用Ansible对服务器执行临时命令自动化和设计功能强大的Ansible剧本将Amazon Web Services...
您将继续学习角色和自定义模块,以实现更好的组织。 谈话视频 即使练习已更新为可与现代版本的Ansible和Python 3配合使用,当前也没有与练习相匹配的视频。 但是,有一些2014年以来的视频,内容涉及基本概念: 慢速...
角色是: 安装Docker(均支持版本,频道和版本固定) 使用PIP安装Docker Compose(支持版本固定) 安装docker PIP封装所以Ansible的docker_*模块工作管理Docker注册表登录凭证配置1个或多个用户以运行Docker而无需...