ITeye博客

Ansible自定义模块

listen-raining · 2016-11-03 17:17 · Ansible · 开源软件 · Markdown

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 =

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
dict_server = 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(,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:
        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: print 'tuple_temp=',tuple_temp if tuple_temp == '2': return True return False

def startDeploy(): dict_temp={} dict_temp = False username = getpass.getuser() if username is not None and username == "mondev": if checkProcesss(): dict_temp = True dict_temp = '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 server_json = dict_server 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
                    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 = True
                    dict_temp = 'deployed success.'
                else:
                    dict_temp = 'Error:deploy fail......'
            else:
                dict_temp = "Error:service return result is not right......"
        else:
            dict_temp = "Error:Can't find useful server link......"
else:
    dict_temp = '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:
        module.exit_json(msg=dict_temp)
    else:
        module.exit_json(msg=dict_temp)    
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)

暂无评论。

评论功能维护中,当前仅展示历史评论。