⑤:jenkins of continuous integration script for automated code deployment and one-click Rollback to the previous version

Source: Internet
Author: User
Tags curl mkdir rollback touch ssh

⑤:jenkins of continuous integration script for automated code deployment and one-click Rollback to the previous version

One: This article uses the way Jenkins invokes shell scripts to get code from a git server, package, deploy to a Web server, remove a Web server from a load balancer, unzip, copy a configuration file, create a soft connection, test each Web server, Add the Web server to the load balancer, roll back to any specified version, one-click Rollback to the previous version and other features, the script is placed in the WWW user home directory and use the WWW user identity, each Web server also uses the WWW user run the Web service, and the UID same Web directory and permissions are consistent, Tighter standardization can lead to safer production environments and higher efficiencies:
1.1: Invoke the shell script in the Jenkins project configuration and prepare for the environment:
1.1.1: #jenkins-Project-Configuration:

1.1.2:www script content in the user home directory:

$ cat code_deploy.sh #!/bin/bash #Dir List Deployment node (that is, what the deployment node needs to do) # mkdir-p/deploy/code/web-demo # mkdir-p/deploy/config/ 
Web-demo/base # mkdir-p/deploy/config/web-demo/other # mkdir/deploy/tmp # mkdir/deploy/tar # chown-r Www.www/deploy # chown-r Www.www/webroot # chown-r www.www/opt/webroot/# chown-r Www.www/webroot # action required on client node # Mkdir/opt/web  Root # mkdir/webroot # chown-r Www.www/webroot # chown-r www.www/opt/webroot/# chown-r Www.www/webroot # [www@ ~]$
Touch/webroot/web-dem # node List server nodes pre_list= "192.168.3.12" # Pre-production node group1_list= "192.168.3.12 192.168.3.13" Group2_list= "192.168.3.13" rollback_list= "192.168.3.12 192.168.3.13" # Log date and time variable log_date= ' date ' +%y-%m-%d ' # If execution is performed later, the time is not fixed, this is the time the log was used log_time= ' date ' +%h-%m-%s "' # code package time variable cdate=$ (date" +%y-%m-%d ") # Once the script executes, it takes a fixed time assignment to the variable, which is fixed ctime=$ (date + "%h-%m-%s") # Shell env script location variables shell_name= "deploy.sh" # Script name shell_dir= "/h ome/www/"# Script path shell_log=" ${shell_dir}/${shell_namE}.log "# Script execution log file path # code env code variable pro_name=" Web-demo "# project name function code_dir="/deploy/code/web-demo "# Updated from version management system 
Config_dir= "/deploy/config/web-demo" # Save configuration files for different projects, a directory is a configuration file or multiple profiles tmp_dir= "/deploy/tmp" # Temp directory for a project Tar_dir= "/deploy/tar" # Package directory Lock_file= "/tmp/deploy.lock" # Lock file path usage () {# Use Help function echo $ "usage: $ [de Ploy |  Rollback [List | emergency | version] "} writelog () {# Write to log function Loginfo=$1 # Enter the parameter as the log echo" ${cdate} ${ctime}: 
    ${sehll_name}: ${loginfo} ">> ${shell_log}} # Lock function Shell_lock () {Touch ${lock_file}} # Unlock function Shell_unlock () {  Rm-f ${lock_file}} # get Code function Code_get () {echo "Code_get" Writelog code_get cd $CODE _dir && git
    Pull # enters the code directory update code, here must be password-free update, this directory only for code updates can not put any other files Cp-rf ${code_dir} ${tmp_dir}/# Temporary save code and rename, package named Time + version number, ready to replicate to the Web server api_verl=$ (git show | grep commit | cut-d "-f2) api_ver=$ (Echo ${api_verl:0:8}) # version number} code_build () { # code compilation function echo Code_build} code_config () {# config file function writelog "Code_config"/bin/cp-rf ${config_dir}/base/* ${tmp_dir}/"${PRO_N AME} "# Place the configuration file in a temporary directory of the native save profile to temporarily save the Code project Pkg_name=" ${pro_name} "_" $API _ver "_" ${cdate}-${ctime} "# define code directory name CD ${t Mp_dir} && MV ${pro_name} ${pkg_name} # Rename code file to web-demo_123-20170629-11-19-10 format} code_tar () {# Package the code function Writelog Code_tar CD ${tmp_dir} && tar czf ${pkg_name}.tar.gz ${pkg_name}--exclude= ". Git" # package directory as a compressed file , facilitates network transmission Writelog "${pkg_name}.tar.gz packaged Success" # Record package success log} CODE_SCP () {# code compression package SCP to client function Writelog " CODE_SCP "for node in $PRE _list;do # Loop server node list SCP ${tmp_dir}/${pkg_name}.tar.gz $node:/opt/webroot/# will compress the code The package is copied to the Web server by the/opt/webroot do for node in $GROUP 1_list;do # Loop server node list SCP ${tmp_dir}/${pkg_name}.tar.gz $n ode:/opt/webroot/# Copy the compressed code package to the Web server's/opt/webroot Done} cluster_node_add () {#将web服务器添加至前端负载 echo cluster_node_a DD} Cluster_node_removE () {# Remove the Web server from the cluster (should not process the business when deploying) Writelog "Cluster_node_remove"} url_test () {url=$1 curl-s--head $URL
        |grep ' OK ' if [$?-ne 0];then Shell_unlock;
    Writelog "Test Error" && exit; fi} Pre_deploy () {# # code decompression deployment function, pre-production node Writelog "Pre_deploy" for node in ${pre_list};d o # Loop pre-production server node list Clust Er_node_remove ${node} # Before deployment Remove the node from the front-end payload echo "Pre_deploy, Cluster_node_remove ${node}" ssh ${node} "CD/ Opt/webroot && tar zxf ${pkg_name}.tar.gz "#分别到web服务器执行压缩包解压命令 ssh ${node}" rm-f/webroot/web-demo && Amp  Ln-s/opt/webroot/${pkg_name}/webroot/web-demo "# Entire automation core, creating soft Connect Done} pre_test () {# Pre-production host Test function for node in ${pre_list};d o # Loop Pre-production host list Curl-s--head http://${node}:9999/index.html | grep "OK" # Test Web Interface access if [$?-eq 0];then # If Access succeeds Writelog "${node} Web Test ok!" # record
                Log echo "${node} Web Test ok!" CLuster_node_add ${node} # After test succeeds call add function to add server to node, writelog "Pre,${node} Add to cluster ok!" # Record add server to cluster log 
                Else # if Access fails Writelog "${node} Test no OK" # log echo "${node} Test not OK"
    Shell_unlock # Call Delete lock file function Break # End deploy Fi done} Group1_deploy () {# code unzip deployment function  
        Writelog "Group1_code_deploy" for node in ${group1_list};d o # Loop production server node list Cluster_node_remove $node echo "group1, Cluster_node_remove $node" ssh ${node} "cd/opt/webroot && tar zxf ${pkg_name}.tar.gz" # respectively To each Web server node to perform the compression package decompression command SSH ${node} "rm-f/webroot/web-demo && ln-s/opt/webroot/${pkg_name}/webroot/web-de Mo "# Entire automation core, create soft connect done SCP ${config_dir}/other/192.168.3.13.server.xml 192.168.3.13:/WEBROOT/WEB-DEMO/SERVER.XM L # The configuration file for the differential project is SCP to this Web server and ends with a project} group1_test () {# Production host Test function for node in ${pre_list};d O # Loop production Host List Curl- S--head Http://${node}:9999/index.html |
            grep "OK" #测试web界面访问 if [$?-eq 0];then #如果访问成功 writelog "${node} Web Test ok!" #记录日志
            echo "Group1_test,${node} Web Test ok!" Cluster_node_add writelog "${node} Add to cluster ok!" #记录将服务器 the log added to the cluster else #如果访问失败 writ Elog "${node} Test no OK" #记录日志 echo "${node} Test no OK" Shell_unlock # Call Delete lock file function bre AK # End Deployment fi done} emergency_code_get () {#获取代码的函数 writelog "Code_get" CD ${code_dir} && git Reset--hard head^ #进入到代码目录更新代码, this must be free of password updates, this directory only for code updates cannot put any other files/bin/cp-rf ${code_dir} ${tmp_dir}/#临时保存代码并重命名, package name is Time + Version number, ready to replicate to Web server api_verl=$ (git show | grep commit | cut-d "-f2) api_ver=$ (Echo ${api_verl:0:8}) #取八位} emerge
        Ncy () {#紧急回退到上一个版本函数 emergency_code_get #执行将代码回退到上一个版本函数 code_build; #如果要编译执行编译函数 code_config; #cp配置文件 Code_tar; #打包 CODE_SCP; #scp到服务器 Cluster_node_remove Pre_deploy; #预生产环境部署 pre_test; #预生产环境测试 Group1_deploy; #生产环境部署 group1_test; #生产环境测试 Code_config; #cp差异文件 #code_test; #代码测试 Shell_unlock #执行完成后删除锁文件} rollback_fun () {for node in $ROLLBACK _list;do # Loop server Node List # Note Be sure to add " Command ssh $node "rm-f/webroot/web-demo && ln-s/opt/webroot/$1/webroot/web-demo" # immediately rolls back to the specified version,
        $ $ specified version parameter echo "${node} rollback success!" DONE} rollback () {# code rollback main function If [-Z $];then shell_unlock # Delete lock file echo "Please input rollback versi
    On "&& exit 3;
        Fi case $ in # take the second parameter as your first parameter list) ls-l/opt/webroot/*.tar.gz;;
        *) Rollback_fun $ ESAC} main () {if [-f $LOCK _file]; then # First determine if the lock file is not in, if there is a lock file exit directly echo "Deploy is running" && exit Deploy_method=$1 # Avoid errors use the first argument of the script as a variable rollback_ver=$2 c ASE $DEPLOY _methodIn deploy) # If the first parameter is deploy, perform the following operations Shell_lock; # Create a lock before performing the deployment. If there are other people executing at the same time, prompt the lock file exists code_get; # get Code Code_build; # If you want to compile and execute the compiler function code_config;    # CP configuration file Code_tar;    # packing CODE_SCP;  # SCP to server Pre_deploy;    # Pre-production environment deployment pre_test; # Pre-production environment Test group1_deploy;   # Production environment Deployment group1_test; # production environment Test Shell_unlock;
        # Delete the lock file after execution is completed;; Rollback) # If the first parameter is rollback perform the following operations Shell_lock;
            # before rolling back is also the first to create a lock file rollback $ROLLBACK _ver; Shell_unlock;
        # execution Complete delete lock file;; Emergency) emergency;
        #紧急回退就不需要参数了, but in the implementation of the time to confirm whether you want to return urgently, to avoid input errors;;
    *) usage; ESAC} main $ $

1.1.4: Modify the current Web page:

[Www@master ~]$ cd Web-demo
[Www@master web-demo]$ echo "

1.4: Roll back to any version:
1.4.1: Where to look for the rollback to the version?:
$ ll/deploy/tmp/#部署服务器, Web server in Nginx-defined directory view version

1.4.3: Performing rollback in Jenkins:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.