美文网首页
centos7 jenkins部署

centos7 jenkins部署

作者: 笨笨翔 | 来源:发表于2019-08-22 14:59 被阅读0次

    引言
      由于现在所在公司还处于手动ssh服务器启动tomcat的发版步骤,版本混乱,人工容易出错。所以这里部署一个jenkins发版。这里只考虑单机部署

    1. 下载最新的jenkins

    # 下载jenkins源
    sudo wget -O /etc/yum.repos.d/jenkins.repo http://jenkins-ci.org/redhat/jenkins.repo
    sudo rpm --import http://pkg.jenkins-ci.org/redhat/jenkins-ci.org.key
    # 使用yum安装jenkins
    sudo yum install jenkins
    

    2. 修改jenkins配置文件

    # 由于公司的安全组策略,不开放8080端口,jenkins默认的是8080端口
    # 修改jenkins的配置文件,默认位置为/etc/sysconfig/jenkins
    sudo vim /etc/sysconfig/jenkins
    JENKINS_PORT="8084" 
    

    3. 启动jenkins

    sudo service start jenkins
    # 启动成功会看到Starting Jenkins ok
    # 如果启动失败可以去看jenkins的具体日志默认位置在/var/log/jenkins/目录下
    cat /var/log/jenkins
    

    4. 访问jenkins

    主机ip:端口,会看到jenkins的欢迎页

    这里要求设置密码并选择安装插件,可以把推荐的插件都安装上,也可以之后安装,这里选择安装。

    5. 安装需要的插件

    git parameter, Git plugin, Pulish Over SSH,等

    6. 部署脚本

    由于公司是一台服务器部署多个tomcat,并且tomcat是根据端口来命名的这里贴上一份python脚本,用于部署服务使用。服务器在腾讯云下,并且用了腾讯与提供的负载均衡。
    所以这里要先取消负载均衡的权重,并在部署完后将权重恢复。

    #!/usr/bin/python
    # -*- coding:utf-8 -*-
    # name : lipengxiang 单服务器部署
    
    
    import os
    import sys
    import time
    import glob
    import telnetlib
    import argparse
    import json
    from tencentcloud.common import credential
    from tencentcloud.common.profile.client_profile import ClientProfile
    from tencentcloud.common.profile.http_profile import HttpProfile
    from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
    from tencentcloud.clb.v20180317 import clb_client, models
    
    
    host = "127.0.0.1"
    # port = ['8081','8082','8083']
    bash_path = "/server/apps"
    secretId = "***************************"
    secretKey = "*********************"
    region = "****************************"
    parser = argparse.ArgumentParser(description='manual to this script')
    parser.add_argument('--id', type=str, default = None)
    parser.add_argument('--port', type=str, default = None)
    parser.add_argument('--loadBalancerId', type=str, default = None)
    parser.add_argument('--listenerId', type=str, default = None)
    parser.add_argument('--locationId', type=str, default = None)
    
    #loadBalancerId 负载均衡id
    #listenerId     监听器id
    #locationId     转发规则id
    
    args = parser.parse_args()
    weightPort = args.port.split(',');
    id = args.id
    loadBalancerId = args.loadBalancerId
    listenerId = args.listenerId
    locationId = args.locationId
    
    # Targets = []
    # for tempPort in weightPort:
    #     map = {'Type':'CVM','InstanceId':id,'Port':tempPort}
    #     Targets.append(map);
    # print Targets
    # targets = json.dumps(Targets)
    
    # 清空tomcat日志
    def clearlog(tomcatPort):
        map(os.remove, glob.glob(bash_path + "/" + tomcatPort + "/logs/catalina.out"))
    
    # 关闭tomcat服务器----------------------------------------------------------
    def shutdown(tomcatPort):
        clearlog(tomcatPort)
        print("tomcat正在关闭,请稍等...")
        os.system(bash_path + "/" + tomcatPort + "/tomcat.sh stop")
        time.sleep(1)
        os.system("kill -9 $(netstat -lnp|grep " + tomcatPort + "| awk '{print $7}' | awk -F/ '{print $1}') ")
        time.sleep(2)
        try:
            tel = telnetlib.Telnet(host, tomcatPort)
            print("关闭tomcat:" + tomcatPort + ", 失败,请手动关闭")
            sys.exit(1)
        except:
            print("关闭tomcat:" + tomcatPort + ", 成功")
            os.system("rm -rf " + bash_path + "/webapps/" + tomcatPort + "/guess")
    
    
    # 启动tomcat服务器----------------------------------------------------------
    def startup(tomcatPort):
        clearlog(tomcatPort)
        print("tomcat正在启动。。。")
        os.chdir(bash_path + "/" + tomcatPort)
        os.system(bash_path + "/" + tomcatPort + "/tomcat.sh start")
        time.sleep(3)
        for k in range(60, 0, -1):
            print (k)
            time.sleep(1)
            # 判断是否启动成功
            rizhi = open(bash_path + "/" + tomcatPort + "/logs/catalina.out", 'r')
            try:
                telnet = telnetlib.Telnet(host, tomcatPort)
                xinxi = rizhi.read()
                xinxi.index("Server startup in")
                print("启动tomcat:" + tomcatPort + "成功,这次算你运气好!")
                rizhi.close()
                flag = 1
                return
            except:
                rizhi.close()
        else:
            print("启动tomcat:" + tomcatPort + "失败,其实早在我预料之内!")
            sys.exit(1)
    
    
    
    
    def updateWeight(weight, tomcatPort):
        try:
            cred = credential.Credential(secretId, secretKey)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "clb.tencentcloudapi.com"
    
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = clb_client.ClbClient(cred, region, clientProfile)
    
            req = models.ModifyTargetWeightRequest()
    
            Targets = []
            map = {'Type': 'CVM', 'InstanceId': id, 'Port': tomcatPort}
            Targets.append(map);
            targets = json.dumps(Targets)
    
            params = '{"LoadBalancerId":"'+loadBalancerId+'","ListenerId":"'+listenerId+'","LocationId":"'+locationId+'","Targets":'+targets+',"Weight":'+weight+'}'
            print("params: " , params)
            req.from_json_string(params)
    
            resp = client.ModifyTargetWeight(req)
            print("weight interface result:" + resp.to_json_string())
            return resp.RequestId
        except TencentCloudSDKException as err:
            print("update weight interface error")
            print(err)
            return
    
    
    #调用验证接口是否成功
    def checkWeight(requestId):
        try:
            cred = credential.Credential(secretId, secretKey)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "clb.tencentcloudapi.com"
    
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = clb_client.ClbClient(cred, region, clientProfile)
    
            req = models.DescribeTaskStatusRequest()
            params = '{"TaskId":"'+requestId+'"}'
            req.from_json_string(params)
    
            resp = client.DescribeTaskStatus(req)
            print(resp.to_json_string())
            for k in range(8, 0, -1):
                time.sleep(1)
                if 2 == resp.Status:
                    resp = client.DescribeTaskStatus(req)
                    print("查询修改权重是否成功:" + resp.to_json_string())
                else:
                    return resp.Status
            else:
                return 2
        except TencentCloudSDKException as err:
            print(err)
    
    
    
    # 重启tomcat服务器----------------------------------------------------------
    def restart():
        for tmpPort in weightPort:
            # update weight 0
            requestId = updateWeight('0',tmpPort)
            result = checkWeight(requestId)
            if 0 != result:
                print 'update weight 0 error,port: '+tmpPort+',result:' + result
                sys.exit(1)
            print 'update weight 0 success,port:' + tmpPort
            # 关闭tomcat
            shutdown(tmpPort)
            # 启动tomcat
            startup(tmpPort)
            requestId = updateWeight('10', tmpPort)
            result = checkWeight(requestId)
            if 0 != result:
                print 'update weight 10 error,port: ' + tmpPort + ',result:' + result
                sys.exit(1)
            print 'update weight 10 success,port:' + tmpPort
    
    
    restart()
    

    相关文章

      网友评论

          本文标题:centos7 jenkins部署

          本文链接:https://www.haomeiwen.com/subject/ehebzqtx.html