CI/CD-JenkinsShareLibery之Pipeline练习

image

一、The back-end

1.1、ATT

#!groovy
@Library('jenkinslib@master') _
 
//build.groovy 封装构建工具
def build = new org.devops.build()
//deploy.groovy
def deploy = new org.devops.deploy()
//toemail.groovy
def toemail = new org.devops.toemail()

pipeline {
    agent any
 
    // 全局环境变量定义
    environment{
        // oacloud-attendance-jar 包名称,如果有变动在此进行修改
        code_jar_name="oacloud-attendance.jar"
 
        // oacloud-attendance-jar代码临时存放路径
        code_build_path="/root/data"
 
        // oacloud-attendance-jar程序运行目录
        code_run_path="/root/jar-data/program/oacloud-attendance"
 
        // oacloud-attendance-jar程序日志目录
        code_log_path="/root/jar-data/logs/oacloud-attendance"
    }
 
    // 选项参数
    options{
        disableConcurrentBuilds()
        skipDefaultCheckout()
        timeout(time: 1, unit: 'HOURS')
        timestamps()
    }
 
    // 各类参数
    parameters {
        // 发布的模块
        choice(
            description: '选择发布模块名称 ?',
            name: 'module',
            choices: ['oacloud-attendance']
            )
 
        // 发布的模块的运行环境
        choice(
            description: '选择发布模块的运行环境 ?',
            name: 'app_env',
            choices: ['test']
            )
 
        // Ansible发布主机群组
        choice(
            description: '选择发布代码的主机(Ansible主机组) ?',
            name: 'inventory',
            choices: ['ATTENDANCE']
            )
 
        // 代码Git地址参数
        choice(
            description: '选择项目仓库地址 ?',
            name: 'srcUrl',
            choices: ['git@192.168.1.190:root/oacloud.git']
            )
 
        // 代码Git分支参数
        choice(
            description: '选择项目仓库分支 ?',
            name: 'branchName',
            choices: ['master','test','dev']
            )
 
        // 编译参数
        choice(
            description: '选择此模块构建的命令 ?',
            name: 'buildShell',
            choices: ['clean package','-v','clean install','clean test']
            )      
        }
 
    stages {
        //代码检出
        stage("Checkout"){
            steps{
                script{
                    try {
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'fe14f540-b7e2-44d8-915f-90a7ebfd99fa', url: "${srcUrl}"]]])
                        println("代码克隆成功-->")
                    } catch(e) {
                        println(e)
                        println("代码克隆失败!")
                        error "代码克隆失败,请及时修复!"
                    }
                }
            }
        }
 
        //代码编译
        stage("Code-Build"){
            steps{
                script{
                    try {
                        mvnHome = tool "M3"
                        sh "${mvnHome}/bin/mvn ${buildShell}"
                        println("代码编译成功-->")
                    } catch(e){
                        println(e)
                        println("代码编译失败!")
                        error "代码编译失败,请及时修复!"
                    }
                }
            }
        }
 
        //代码编译结果jar包判断,并存放到指定路径中
        stage("Build-Code-Test"){
            steps{
                sh '''#!/bin/bash
                    # module_name=oacloud-attendance,oacloud-common-service,oacloud-eureka,oacloud-organization,oacloud-permissions,oacloud-salary,oacloud-gateway,oacloud-performance,oacloud-process,oacloud-user
                     for i in `ls -d ${WORKSPACE}/oacloud-*`;do
                        echo "工作目录中所有的应用目录如下 ${i} -->"
                        cd ${i} && find ./target  -name '*.jar'
                        if [ $? == 0 ];then
                            echo "$i 代码编译成功-->"
                            #if [ -d ${code_build_path} ];then
                            #    mkdir -p ${code_build_path}
                            #    cd ${i}/target && cp *.jar /
                            #fi
                            cd ${i}/target && cp *.jar ${code_build_path}
                        else
                            echo "$i 代码编译失败!"
                            exit 1
                        fi
                    done
                '''  
            }
        }
        // Ansible-Copy模块将代码从jenkins临时存放处分发到目标主机
        stage("Ansible-Copy"){
            steps{
                script{
                    try {
                        //历史垃圾清理,仅保留最近一版
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'rm -rf ${code_run_path}/${code_jar_name}.* '")
                        println("程序 ${module} - ${code_jar_name} - 构建历史清理Ansible - ${inventory}群组 --> ")
 
                        deploy.AnsibleDeploy("${inventory}","-m copy -a 'src=${code_build_path}/${code_jar_name} dest=${code_run_path}/ backup=yes'")
                        println("程序 ${module} - ${code_jar_name} - 已成功经发送至Ansible - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Copy阶段失败!")
                        error "执行Ansible-Copy阶段失败,请及时修复!"
                    } 
                }
            }
        }
        // Ansible-Service模块,连接目标主机进行服务重启
        stage("Ansible-Service"){
            steps{
                 // sh '''#!/bin/bash
                 //   echo "---------------------   ${app_env}"
                 //   # 判断systemd服务
                 //   if [[ `ansible ${inventory} -m script -a 'chdir=/usr/lib/systemd/system/${module}.service ls'` && echo $?  ]];then
                     
                 //   fi
                 // '''
                script{
                    try {
                        deploy.AnsibleDeploy("${inventory}","-m service -a 'name=${module} state=restarted'")
                        println("程序 ${module} - ${code_jar_name} - 已成功经发送之Ansible - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Service阶段失败!")
                        error "执行Ansible-Service失败,请及时修复!"
                    } 
                }
            }
        }
 
       // Ansible-Service模块,连接目标主机进行服务状态检查
        stage("Ansible-Status"){
            steps{
                script{
                     
                    println("流水休眠5s,进行状态检查!")
                    sleep(5)
                     
                    try {
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'service ${module} status'")
                        println("程序 ${module} - ${code_jar_name} - 已经在Ansible - ${inventory}群组重启 --> ")
 
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Status阶段失败!")
                        error "执行Ansible-Status失败,请及时修复!"
                    } 
                }
            }
        }
    }
     
    // 构建后操作
    post {
        // 总是执行
        always {
            script {
                println("always - 总是执行步骤正常 -->")
            }
        }
        // 构建成功执行
        success {
            script {
                currentBuild.description += "\n 构建成功!"
                println("success - 此流水线构建成功 -->")
                // toemail.Email("流水线构建成功",userEmail)
            }
        }
        //构建失败执行
        failure {
            script {
                currentBuild.description += "\n 构建失败!"
                println("failure - 此流水线构建失败 -->")
                // toemail.Email("流水线构建失败",userEmail)
            }
        }
        // 取消后执行
        aborted {
            script {
                currentBuild.description += "\n 构建取消!"
                println("aborted - 此流水线构建取消 -->")
                // toemail.Email("流水线构建取消",userEmail)
            }
        }
    }
}

1.2、common-server

#!groovy
@Library('jenkinslib@master') _
 
//build.groovy 封装构建工具
def build = new org.devops.build()
//deploy.groovy
def deploy = new org.devops.deploy()
//toemail.groovy
def toemail = new org.devops.toemail()
  
pipeline {
    agent any
 
    // 全局环境变量定义
    environment{
        // oacloud-common-service-jar 包名称,如果有变动在此进行修改
        code_jar_name="oacloud-common-service.jar"
 
        // oacloud-common-service-jar代码临时存放路径
        code_build_path="/root/data"
 
        // oacloud-attendance-jar程序运行目录
        code_run_path="/root/jar-data/program/oacloud-common-service"
 
        // oacloud-common-service-jar程序日志目录
        code_log_path="/root/jar-data/logs/oacloud-common-service"
    }
 
    // 选项参数
    options{
        disableConcurrentBuilds()
        skipDefaultCheckout()
        timeout(time: 1, unit: 'HOURS')
        timestamps()
    }
 
    // 各类参数
    parameters {
        // 发布的模块
        choice(
            description: '选择发布模块名称 ?',
            name: 'module',
            choices: ['oacloud-common-service']
            )
 
        // 发布的模块的运行环境
        choice(
            description: '选择发布模块的运行环境 ?',
            name: 'app_env',
            choices: ['test']
            )
 
        // Ansible发布主机群组
        choice(
            description: '选择发布代码的主机(Ansible主机组) ?',
            name: 'inventory',
            choices: ['COMMON-SERVICE']
            )
 
        // 代码Git地址参数
        choice(
            description: '选择项目仓库地址 ?',
            name: 'srcUrl',
            choices: ['git@192.168.1.190:root/oacloud.git']
            )
 
        // 代码Git分支参数
        choice(
            description: '选择项目仓库分支 ?',
            name: 'branchName',
            choices: ['master','test','dev']
            )
 
        // 编译参数
        choice(
            description: '选择此模块构建的命令 ?',
            name: 'buildShell',
            choices: ['clean package','-v','clean install','clean test']
            )      
        }
 
     stages {
        //代码检出
        stage("Checkout"){
            steps{
                script{
                    try {
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'fe14f540-b7e2-44d8-915f-90a7ebfd99fa', url: "${srcUrl}"]]])
                        println("代码克隆成功-->")
                    } catch(e) {
                        println(e)
                        println("代码克隆失败!")
                        error "代码克隆失败,请及时修复!"
                    }
                }
            }
        }
 
        //代码编译
        stage("Code-Build"){
            steps{
                script{
                    try {
                        mvnHome = tool "M3"
                        sh "${mvnHome}/bin/mvn ${buildShell}"
                        println("代码编译成功-->")
                    } catch(e){
                        println(e)
                        println("代码编译失败!")
                        error "代码编译失败,请及时修复!"
                    }
                }
            }
        }
 
        //代码编译结果jar包判断,并存放到指定路径中
        stage("Build-Code-Test"){
            steps{
                sh '''#!/bin/bash
                    # module_name=oacloud-attendance,oacloud-common-service,oacloud-eureka,oacloud-organization,oacloud-permissions,oacloud-salary,oacloud-gateway,oacloud-performance,oacloud-process,oacloud-user
                     for i in `ls -d ${WORKSPACE}/oacloud-*`;do
                        echo "工作目录中所有的应用目录如下 ${i} -->"
                        cd ${i} && find ./target  -name '*.jar'
                        if [ $? == 0 ];then
                            echo "$i 代码编译成功-->"
                            #if [ -d ${code_build_path} ];then
                            #    mkdir -p ${code_build_path}
                            #    cd ${i}/target && cp *.jar /
                            #fi
                            cd ${i}/target && cp *.jar ${code_build_path}
                        else
                            echo "$i 代码编译失败!"
                            exit 1
                        fi
                    done
                '''  
            }
        }
        // Ansible-Copymo模块将代码从jenkins临时存放处分发到目标主机
        stage("Ansible-Copy"){
            steps{
                script{
                    try {
                        //历史垃圾清理,仅保留最近一版
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'rm -rf ${code_run_path}/${code_jar_name}.* '")
                        println("程序 ${module} - ${code_jar_name} - 构建历史清理Ansible - ${inventory}群组 --> ")
 
                        deploy.AnsibleDeploy("${inventory}","-m copy -a 'src=${code_build_path}/${code_jar_name} dest=${code_run_path}/ backup=yes'")
                        println("程序 ${module} - ${code_jar_name} - 已成功经发送至Ansible - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Copy阶段失败!")
                        error "执行Ansible-Copy阶段失败,请及时修复!"
                    } 
                }
            }
        }
        // Ansible-Service模块,连接目标主机进行服务重启
        stage("Ansible-Service"){
            steps{
                 // sh '''#!/bin/bash
                 //   echo "---------------------   ${app_env}"
                 //   # 判断systemd服务
                 //   if [[ `ansible ${inventory} -m script -a 'chdir=/usr/lib/systemd/system/${module}.service ls'` && echo $?  ]];then
                     
                  //  fi
                // '''
                script{
                    try {
                        deploy.AnsibleDeploy("${inventory}","-m service -a 'name=${module} state=restarted'")
                        println("程序 ${module} - ${code_jar_name} - 已成功经发送之Ansible - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Service阶段失败!")
                        error "执行Ansible-Service失败,请及时修复!"
                    } 
                }
            }
        }
 
       // Ansible-Service模块,连接目标主机进行服务状态检查
        stage("Ansible-Status"){
            steps{
                script{
                     
                    println("流水休眠5s,进行状态检查!")
                    sleep(5)
                     
                    try {
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'service ${module} status'")
                        println("程序 ${module} - ${code_jar_name} - 已经在Ansible - ${inventory}群组重启 --> ")
 
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Status阶段失败!")
                        error "执行Ansible-Status失败,请及时修复!"
                    } 
                }
            }
        }
    }
     
    // 构建后操作
    post {
        // 总是执行
        always {
            script {
                println("always - 总是执行步骤正常 -->")
            }
        }
        // 构建成功执行
        success {
            script {
                currentBuild.description += "\n 构建成功!"
                println("success - 此流水线构建成功 -->")
                // toemail.Email("流水线构建成功",userEmail)
            }
        }
        //构建失败执行
        failure {
            script {
                currentBuild.description += "\n 构建失败!"
                println("failure - 此流水线构建失败 -->")
                // toemail.Email("流水线构建失败",userEmail)
            }
        }
        // 取消后执行
        aborted {
            script {
                currentBuild.description += "\n 构建取消!"
                println("aborted - 此流水线构建取消 -->")
                // toemail.Email("流水线构建取消",userEmail)
            }
        }
    }
}

1.3、eureka

#!groovy
@Library('jenkinslib@master') _
 
//build.groovy 封装构建工具
def build = new org.devops.build()
//deploy.groovy
def deploy = new org.devops.deploy()
//toemail.groovy
def toemail = new org.devops.toemail()
  
pipeline {
    agent any
 
    // 全局环境变量定义
    environment{
        // oacloud-eureka-jar 包名称,如果有变动在此进行修改
        code_jar_name="oacloud-eureka.jar"
 
        // oacloud-eureka-jar代码临时存放路径
        code_build_path="/root/data"
 
        // oacloud-attendance-jar程序运行目录
        code_run_path="/root/jar-data/program/oacloud-eureka"
 
        // oacloud-attendance-jar程序日志目录
        code_log_path="/root/jar-data/logs/oacloud-eureka"
    }
 
    // 选项参数
    options{
        disableConcurrentBuilds()
        skipDefaultCheckout()
        timeout(time: 1, unit: 'HOURS')
        timestamps()
    }
 
    // 各类参数
    parameters {
        // 发布的模块
        choice(
            description: '选择发布模块名称 ?',
            name: 'module',
            choices: ['oacloud-eureka']
            )
 
        // 发布的模块的运行环境
        choice(
            description: '选择发布模块的运行环境 ?',
            name: 'app_env',
            choices: ['test']
            )
 
        // Ansible发布主机群组
        choice(
            description: '选择发布代码的主机(Ansible主机组) ?',
            name: 'inventory',
            choices: ['EUREKA']
            )
 
        // 代码Git地址参数
        choice(
            description: '选择项目仓库地址 ?',
            name: 'srcUrl',
            choices: ['git@192.168.1.190:root/oacloud.git']
            )
 
        // 代码Git分支参数
        choice(
            description: '选择项目仓库分支 ?',
            name: 'branchName',
            choices: ['master','test','dev']
            )
 
        // 编译参数
        choice(
            description: '选择此模块构建的命令 ?',
            name: 'buildShell',
            choices: ['clean package','-v','clean install','clean test']
            )      
        }
 
    stages {
        //代码检出
        stage("Checkout"){
            steps{
                script{
                    try {
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'fe14f540-b7e2-44d8-915f-90a7ebfd99fa', url: "${srcUrl}"]]])
                        println("代码克隆成功-->")
                    } catch(e) {
                        println(e)
                        println("代码克隆失败!")
                        error "代码克隆失败,请及时修复!"
                    }
                }
            }
        }
 
        //代码编译
        stage("Code-Build"){
            steps{
                script{
                    try {
                        mvnHome = tool "M3"
                        sh "${mvnHome}/bin/mvn ${buildShell}"
                        println("代码编译成功-->")
                    } catch(e){
                        println(e)
                        println("代码编译失败!")
                        error "代码编译失败,请及时修复!"
                    }
                }
            }
        }
 
        //代码编译结果jar包判断,并存放到指定路径中
        stage("Build-Code-Test"){
            steps{
                sh '''#!/bin/bash
                    # module_name=oacloud-attendance,oacloud-common-service,oacloud-eureka,oacloud-organization,oacloud-permissions,oacloud-salary,oacloud-gateway,oacloud-performance,oacloud-process,oacloud-user
                     for i in `ls -d ${WORKSPACE}/oacloud-*`;do
                        echo "工作目录中所有的应用目录如下 ${i} -->"
                        cd ${i} && find ./target  -name '*.jar'
                        if [ $? == 0 ];then
                            echo "$i 代码编译成功-->"
                            #if [ -d ${code_build_path} ];then
                            #    mkdir -p ${code_build_path}
                            #    cd ${i}/target && cp *.jar /
                            #fi
                            cd ${i}/target && cp *.jar ${code_build_path}
                        else
                            echo "$i 代码编译失败!"
                            exit 1
                        fi
                    done
                '''  
            }
        }
        // Ansible-Copymo模块将代码从jenkins临时存放处分发到目标主机
        stage("Ansible-Copy"){
            steps{
                script{
                    try {
                        //历史垃圾清理,仅保留最近一版
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'rm -rf ${code_run_path}/${code_jar_name}.* '")
                        println("程序 ${module} - ${code_jar_name} - 构建历史清理Ansible - ${inventory}群组 --> ")
 
                        deploy.AnsibleDeploy("${inventory}","-m copy -a 'src=${code_build_path}/${code_jar_name} dest=${code_run_path}/ backup=yes'")
                        println("程序 ${module} - ${code_jar_name} - 已成功经发送至Ansible - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Copy阶段失败!")
                        error "执行Ansible-Copy阶段失败,请及时修复!"
                    } 
                }
            }
        }
        // Ansible-Service模块,连接目标主机进行服务重启
        stage("Ansible-Service"){
            steps{
                 // sh '''#!/bin/bash
                 //   echo "---------------------   ${app_env}"
                 //   # 判断systemd服务
                 //   if [[ `ansible ${inventory} -m script -a 'chdir=/usr/lib/systemd/system/${module}.service ls'` && echo $?  ]];then
                     
                  //  fi
                // '''
                script{
                    try {
                        deploy.AnsibleDeploy("${inventory}","-m service -a 'name=${module} state=restarted'")
                        println("程序 ${module} - ${code_jar_name} - 已成功经发送之Ansible - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Service阶段失败!")
                        error "执行Ansible-Service失败,请及时修复!"
                    } 
                }
            }
        }
 
       // Ansible-Service模块,连接目标主机进行服务状态检查
        stage("Ansible-Status"){
            steps{
                script{
                     
                    println("流水休眠5s,进行状态检查!")
                    sleep(5)
                     
                    try {
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'service ${module} status'")
                        println("程序 ${module} - ${code_jar_name} - 已经在Ansible - ${inventory}群组重启 --> ")
 
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Status阶段失败!")
                        error "执行Ansible-Status失败,请及时修复!"
                    } 
                }
            }
        }
    }
     
    // 构建后操作
    post {
        // 总是执行
        always {
            script {
                println("always - 总是执行步骤正常 -->")
            }
        }
        // 构建成功执行
        success {
            script {
                currentBuild.description += "\n 构建成功!"
                println("success - 此流水线构建成功 -->")
                // toemail.Email("流水线构建成功",userEmail)
            }
        }
        //构建失败执行
        failure {
            script {
                currentBuild.description += "\n 构建失败!"
                println("failure - 此流水线构建失败 -->")
                // toemail.Email("流水线构建失败",userEmail)
            }
        }
        // 取消后执行
        aborted {
            script {
                currentBuild.description += "\n 构建取消!"
                println("aborted - 此流水线构建取消 -->")
                // toemail.Email("流水线构建取消",userEmail)
            }
        }
    }
}

二、The front end

2.1、form

#!groovy
@Library('jenkinslib@master') _
 
//build.groovy 封装构建工具
def build = new org.devops.build()
//deploy.groovy
def deploy = new org.devops.deploy()
//toemail.groovy
def toemail = new org.devops.toemail()
 
pipeline {
    agent any
 
    // 全局环境变量定义
    environment{
        // 事先准备好的前端 oawebsystem的配置文件 setting.js
        configure_js="/root/config/config.js"
 
        // 事先准备好的前端环境参数.env
        // configure_env="/root/setting/.env"
 
        // 前端代码存放目录
        code_run_path="/root/nginx/html/form"
    }     
 
    // 选项参数
    options{
        disableConcurrentBuilds()
        skipDefaultCheckout()
        timeout(time: 1, unit: 'HOURS')
        timestamps()
    }
 
    // 各类参数
    parameters {
 
        // 可选择性是否需要邮件通知
        //string(
        //    description: '可选择性QQ邮件通知功能 ?',
        //    name: 'userEmail',
        //    defaultValue: '1284808408@qq.com',
        //    )
 
        // 发布的模块
        choice(
            description: '选择发布模块名称 ?',
            name: 'module',
            choices: ['oacloud-oaform']
            )
 
        // 发布的模块的运行环境
        choice(
            description: '选择发布模块的运行环境 ?',
            name: 'app_env',
            choices: ['test']
            )
 
        // Ansible发布主机群组
        choice(
            description: '选择发布代码的主机(Ansible主机组) ?',
            name: 'inventory',
            choices: ['OAFORM']
            )
 
        // 代码Git地址参数
        choice(
            description: '选择项目仓库地址 ?',
            name: 'srcUrl',
            choices: ['git@192.168.1.190:daizhe/form.git']
            )
 
        // 代码Git分支参数
        choice(
            description: '选择项目仓库分支 ?',
            name: 'branchName',
            choices: ['master','test','dev']
            )
 
        // 编译参数
        choice(
           description: '选择此模块构建的命令 ?',
            name: 'docker_id',
            choices: ['xxxxxxxxxxx']
            )
 
        // 此处为项目.env配置的 vue_api 地址
        choice(
            description: '选择.env配置的 vue_api 地址 ?',
            name: 'api_address',
            choices: ['47.89.16.50']
            )    
        }
 
 
    stages {
 
        //代码检出
        stage("Checkout"){
            steps{
                script{
                    try {
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'fe14f540-b7e2-44d8-915f-90a7ebfd99fa', url: "${srcUrl}"]]])
                        println("代码克隆成功-->")
                    } catch(e) {
                        println(e)
                        println("代码克隆失败!")
                        error "代码克隆失败,请及时修复!"
                    }
                }
            }
        }
 
        // Ansible-Copy-Setting.js
        stage("Config & ENV"){
            steps{
                script {
                    try {
                        sh'''#!/bin/bash
                        echo "将Jenkins-Server端准备好的${configure_js} 拷贝到 ${WORKSPACE}/config/ 目录下!"
                        cp -f ${configure_js} ${WORKSPACE}/config/
                        if [ $? == 0 ]
                        then
                            echo "已成功将Jenkins-Server端准备好的${configure_js} 拷贝到 ${WORKSPACE}/config/ 目录下!"
                            sed -i "/^var OaBaseDistPath =/cvar OaBaseDistPath = \'${WORKSPACE}/form\'" ${WORKSPACE}/config/config.js
                            sed -i "/baseUrl:/cbaseUrl: \'http://${api_address}/gateway\'" ${WORKSPACE}/config/config.js
                            if [ $? == 0 ];then
                                echo "目前 config.js 的API链接为:baseUrlL=http://${api_address}/gateway"
                            else
                                echo "配置 ${WORKSPACE}/config/config.js 文件失败 -->"
                                exit 1
                            fi
                        else
                            echo "拷贝 ${configure_js} 到 ${WORKSPACE}/src/config/ 目录失败 -->"
                        fi
                        '''
                   } catch(e){
                       println(e)
                       error "Setting & ENV失败,请及时修复!"
                   }
                }
            }
        }
 
        // Code-build
        stage("Build-Code-Test"){
            steps{
                script{
                    try {
                        npmHome = tool "NPM"
                        //sh "cd ${WORKSPACE} && export PATH=\$PATH:${npmHome}/bin && ${npmHome}/bin/npm install --registry=https://registry.npm.taobao.org"
                        //sh "cd ${WORKSPACE} && export PATH=\$PATH:${npmHome}/bin && ${npmHome}/bin/npm run build"
                    } catch(e){
                        error "代码编译失败,请及时修复!"
                    }
                }
            }
        }
 
        // Code-Tar
        stage("Tar-Code-Test"){
            steps{
                script{
                    script {
                        try {
                            sh 'cd ${WORKSPACE} && tar cvzf code-form.tar.gz ./form'
                            println("代码打包成功-->")
                        } catch(e){
                            println(e)
                            println("代码打包失败!")
                            error "Tar-Code-Test失败,请及时修复!"
                        }
                    }
                }
            }
        }
 
        // Ansible-Code-Copy
         stage("Ansible-Copy"){
            steps{
                script{
                    try {
                        // 前端代码存放路径创建
                        deploy.AnsibleDeploy("${inventory}","-m file -a 'dest=${code_run_path} state=directory'")
 
                        //历史垃圾清理,仅保留最近一版
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'rm -rf ${code_run_path}/code-form.tar.gz.* '")
                        // println("前端 ${module} - code-form.tar.gz - 构建历史清理Ansible - ${inventory}群组 --> ")
 
                        deploy.AnsibleDeploy("${inventory}","-m copy -a 'src=${WORKSPACE}/code-form.tar.gz dest=${code_run_path}/ backup=yes'")
                        println("前端 ${module} - code-form.tar.gz - 已成功经发送至Ansible - ${inventory}群组 --> ")
 
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'cd ${code_run_path} && tar xvf code-form.tar.gz'")
                        println("前端 ${module} - code-form.tar.gz - 已成功解压 - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Copy阶段失败!")
                        error "执行Ansible-Copy阶段失败,请及时修复!"
                    } 
                }
            }
        }
 
        // Ansible-Service
         stage("Ansible-Service"){
            steps{
                script{
                    try {
                        // deploy.AnsibleDeploy("${inventory}","-m service -a 'name=nginx state=restarted'")
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'docker exec ${docker_id} nginx -s reload'")
                        println("前端 ${module} - 已成功重启对Docker-Nginx-${docker_id} - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Service阶段失败!")
                        error "执行Ansible-Service阶段失败,请及时修复!"
                    } 
                }
            }
        }
    }
     
    // 构建后操作
    post {
        // 总是执行
        always {
            script {
                println("always - 总是执行步骤正常 -->")
            }
        }
        // 构建成功执行
        success {
            script {
                currentBuild.description += "\n 构建成功!"
                println("success - 此流水线构建成功 -->")
                // toemail.Email("流水线构建成功",userEmail)
            }
        }
        //构建失败执行
        failure {
            script {
                currentBuild.description += "\n 构建失败!"
                println("failure - 此流水线构建失败 -->")
                // toemail.Email("流水线构建失败",userEmail)
            }
        }
        // 取消后执行
        aborted {
            script {
                currentBuild.description += "\n 构建取消!"
                println("aborted - 此流水线构建取消 -->")
                // toemail.Email("流水线构建取消",userEmail)
            }
        }
    }
}

2.2、websystem

#!groovy
@Library('jenkinslib@master') _
 
//build.groovy 封装构建工具
def build = new org.devops.build()
//deploy.groovy
def deploy = new org.devops.deploy()
//toemail.groovy
def toemail = new org.devops.toemail()

pipeline {
    agent any
 
    // 全局环境变量定义
    environment{
        // 事先准备好的前端 oawebsystem的配置文件 setting.js
        configure_js="/root/setting/setting.js"
 
        // 事先准备好的前端环境参数.env
        configure_env="/root/setting/.env"
 
        // 前端代码存放目录
        code_run_path="/root/nginx/html/dist"
    }     
 
    // 选项参数
    options{
        disableConcurrentBuilds()
        skipDefaultCheckout()
        timeout(time: 1, unit: 'HOURS')
        timestamps()
    }
 
    // 各类参数
    parameters {
 
        // 可选择性是否需要邮件通知
        //string(
        //    description: '可选择性QQ邮件通知功能 ?',
        //    name: 'userEmail',
        //    defaultValue: '1284808408@qq.com',
        //    )
 
        // 发布的模块
        choice(
            description: '选择发布模块名称 ?',
            name: 'module',
            choices: ['oacloud-oawebsystem']
            )
 
        // 发布的模块的运行环境
        choice(
            description: '选择发布模块的运行环境 ?',
            name: 'app_env',
            choices: ['test']
            )
 
        // Ansible发布主机群组
        choice(
            description: '选择发布代码的主机(Ansible主机组) ?',
            name: 'inventory',
            choices: ['OAWEBSYSTEM']
            )
 
        // 代码Git地址参数
        choice(
            description: '选择项目仓库地址 ?',
            name: 'srcUrl',
            choices: ['git@192.168.1.190:daizhe/oawebsystem.git']
            )
 
        // 代码Git分支参数
        choice(
            description: '选择项目仓库分支 ?',
            name: 'branchName',
            choices: ['master','test','dev']
            )
 
        // 编译参数
        choice(
           description: '选择此模块构建的命令 ?',
            name: 'docker_id',
            choices: ['xxxxxxxxxxx']
            )
 
        // 此处为项目.env配置的 vue_api 地址
        choice(
            description: '选择.env配置的 vue_api 地址 ?',
            name: 'api_address',
            choices: ['47.89.16.50']
            )    
        }
 
 
    stages {
 
        //代码检出
        stage("Checkout"){
            steps{
                script{
                    try {
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'fe14f540-b7e2-44d8-915f-90a7ebfd99fa', url: "${srcUrl}"]]])
                        println("代码克隆成功-->")
                    } catch(e) {
                        println(e)
                        println("代码克隆失败!")
                        error "代码克隆失败,请及时修复!"
                    }
                }
            }
        }
 
        // Ansible-Copy-Setting.js
        stage("Setting & ENV"){
            steps{
                script {
                    try {
                        sh'''#!/bin/bash
                        echo "将Jenkins-Server端准备好的${configure_js} 拷贝到 ${WORKSPACE}/src/config/ 目录下!"
                        cp -f ${configure_js} ${WORKSPACE}/src/config/
                        if [ $? == 0 ];then
                            echo "已成功将Jenkins-Server端准备好的${configure_js} 拷贝到 ${WORKSPACE}/src/config/ 目录下!"
                            sed -i "/^VUE_APP_API_BASE_URL=/cVUE_APP_API_BASE_URL=http://${api_address}/gateway" ${configure_env}
                            cp ${configure_env} /${WORKSPACE}
                            if [ $? == 0 ];then
                                echo "目前 .env 的API链接为:VUE_APP_API_BASE_URL=http://${api_address}/gateway"
                            else
                                echo "拷贝 ${configure_env} 到 ${WORKSPACE}/src/config/ 目录失败 -->"
                                exit 1
                            fi
                        else
                            echo "拷贝 ${configure_js} 到 ${WORKSPACE}/src/config/ 目录失败 -->"
                            exit 1
                        fi
                        '''
                   } catch(e){
                       println(e)
                       error "Setting & ENV失败,请及时修复!"
                   }
                }
            }
        }
 
        // Code-build
        stage("Build-Code-Test"){
            steps{
                script{
                    try {
                        npmHome = tool "NPM"
                        //sh "cd ${WORKSPACE} && export PATH=\$PATH:${npmHome}/bin && ${npmHome}/bin/npm install --registry=https://registry.npm.taobao.org"
                        //sh "cd ${WORKSPACE} && export PATH=\$PATH:${npmHome}/bin && ${npmHome}/bin/npm run build"
                    } catch(e){
                        error "代码编译失败,请及时修复!"
                    }
                }
            }
        }
 
        // Code-Tar
        stage("Tar-Code-Test"){
            steps{
                script{
                    script {
                        try {
                            sh 'cd ${WORKSPACE} && tar cvzf code-dist.tar.gz ./dist'
                            println("代码打包成功-->")
                        } catch(e){
                            println(e)
                            println("代码打包失败!")
                            error "Tar-Code-Test失败,请及时修复!"
                        }
                    }
                }
            }
        }
 
        // Ansible-Code-Copy
         stage("Ansible-Copy"){
            steps{
                script{
                    try {
                        // 前端代码存放路径创建
                        deploy.AnsibleDeploy("${inventory}","-m file -a 'dest=${code_run_path} state=directory'")
 
                        //历史垃圾清理,仅保留最近一版
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'rm -rf ${code_run_path}/code-dist.tar.gz.* '")
                        // println("前端 ${module} - code-dist.tar.gz - 构建历史清理Ansible - ${inventory}群组 --> ")
 
                        deploy.AnsibleDeploy("${inventory}","-m copy -a 'src=${WORKSPACE}/code-dist.tar.gz dest=${code_run_path}/ backup=yes'")
                        println("前端 ${module} - code-dist.tar.gz - 已成功经发送至Ansible - ${inventory}群组 --> ")
 
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'cd ${code_run_path} && tar xvf code-dist.tar.gz'")
                        println("前端 ${module} - code-dist.tar.gz - 已成功解压 - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Copy阶段失败!")
                        error "执行Ansible-Copy阶段失败,请及时修复!"
                    } 
                }
            }
        }
 
        // Ansible-Service
         stage("Ansible-Service"){
            steps{
                script{
                    try {
                        // deploy.AnsibleDeploy("${inventory}","-m service -a 'name=nginx state=restarted'")
                        deploy.AnsibleDeploy("${inventory}","-m shell -a 'docker exec ${docker_id} nginx -s reload'")
                        println("前端 ${module} - 已成功重启对Docker-Nginx-${docker_id} - ${inventory}群组 --> ")
                    } catch(e) {
                        println(e)
                        println("执行Ansible-Service阶段失败!")
                        error "执行Ansible-Service阶段失败,请及时修复!"
                    } 
                }
            }
        }
    }
     
    // 构建后操作
    post {
        // 总是执行
        always {
            script {
                println("always - 总是执行步骤正常 -->")
            }
        }
        // 构建成功执行
        success {
            script {
                currentBuild.description += "\n 构建成功!"
                println("success - 此流水线构建成功 -->")
                // toemail.Email("流水线构建成功",userEmail)
            }
        }
        //构建失败执行
        failure {
            script {
                currentBuild.description += "\n 构建失败!"
                println("failure - 此流水线构建失败 -->")
                // toemail.Email("流水线构建失败",userEmail)
            }
        }
        // 取消后执行
        aborted {
            script {
                currentBuild.description += "\n 构建取消!"
                println("aborted - 此流水线构建取消 -->")
                // toemail.Email("流水线构建取消",userEmail)
            }
        }
    }
}
posted @ 2021-05-09 18:43  SRE运维充电站  阅读(80)  评论(0编辑  收藏  举报