Ansible自定义模块

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值