IT必备技能软件测试

Jenkins流水线--部署多模块maven项目(推荐)

2020-11-17  本文已影响0人  阿B咬佢只鸡
Jenkins流水线各步骤分解

Jenkins+Springboot+gitlab+maven+jdk+docker

目录

多模块maven项目结构大概如下:

cfw-project  #父工程
       -canfu-eureka    #子工程(1)
       -canfu-provider  #子工程(2)
       -canfu-supplier  #子工程(n)
             -src
             -pom.xml
       -pom.xml
       -Dockerfile_config  #存放各子工程Dockerfile
       -Deploy.sh          #远程部署脚本

1、编写Jenkinsfile,Dockerfile,Deploy.sh

编写声明式Jenkinsfile

pipeline {
    agent any
    environment {
        registryUrl= "192.168.1.110:5000"       //搭建docker私有仓库(Harbor)或者 用DockerHub 又或者用云平台的“容器镜像服务”
        registry_user= "xxx"
        registry_pass= "xxx"
    }
    options {
        timestamps()    //设置在项目打印日志时带上对应时间
        disableConcurrentBuilds()   //不允许同时执行流水线,被用来防止同时访问共享资源等
        timeout(time: 3, unit: 'MINUTES')   // 设置流水线运行超过n分钟,Jenkins将中止流水线
        buildDiscarder(logRotator(numToKeepStr: '20'))   // 表示保留n次构建历史
    }

    //gitlab  webhook触发器
    //代码推到gitlab上后,所有子项目将被触发构建,不可取,待优化启用
    //triggers{
    //   gitlab( triggerOnPush: true,                       //代码有push动作就会触发job
    //       triggerOnMergeRequest: true,                   //代码有merge动作就会触发job
    //        branchFilterType: "NameBasedFilter",          //只有符合条件的分支才会触发构建 “ALL/NameBasedFilter/RegexBasedFilter”
    //        includeBranchesSpec: "${JOB_BASE_NAME}")      //基于branchFilterType值,输入期望包括的分支的规则
    //}

    stages{
        stage('Print Message') {      //打印信息
            steps {
                echo '打印信息'
                echo "Project_Pipeline_name: ${JOB_NAME}"
                echo "Project_module_name: ${PROJECT_NAME}"
                echo "workspace: ${WORKSPACE}"
                echo "branch: ${Branch_name}"           //gitlab分支名
                echo "build_id: ${BUILD_ID}"
                echo "target_action: ${action}"
                echo "registryUrl: ${registryUrl}"
                echo "image_repository: ${registryUrl}/${Project_name}"
           }
        }
        stage ('Checkout'){         //拉取代码
            steps{
                echo '拉取代码'
                script {
                    if ( action == 'deploy' ) {    //判断当action == 'deploy' 时,才执行此stage
                        checkout([$class: 'GitSCM', branches: [[name: '${Branch_name}']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [],
                            userRemoteConfigs: [[credentialsId: '7ff3778d-124f-40b1-a5e6-05d600a7e59e', //gitlab登录令牌,如何设置自行搜索方法
                            url: 'http://192.168.1.110/java/pipeline-project.git']]])    //gitlab项目clone地址
                    }
                }
            }
        }
        stage('Packaging project') {        //mvn打包
            steps {
                echo 'mvn打包子项目'
                script {
                    if ( action == 'deploy' ) {
                        try {    //此步骤执行失败,将终止流水线工作
                            sh 'source /etc/profile && mvn clean package -pl ${Project_name} -am -amd -P${Branch_name} -Dmaven.test.skip=true'
                            //“-pl”指定子项目名称 ; “-P”指定使用哪个环节的配置文件(-Ptest即使用文件application-test.yml)
                        } catch (err) {
                            echo 'Packaging project failed & End of Pipeline!!!'
                            //echo '可能原因:(1)上一次失败构建或中断构建项目后,工作目录${WORKSPACE}没有清理(可选择手动执行rm -rf ${WORKSPACE}/*)'
                        }
                    }
                }
            }
        }
        stage('Build & Push Image to Harbor') {      //构建,推送镜像
            steps {
                echo '构建,推送镜像到docker镜像仓库'
                dir ('./') {       //指定工作目录(默认为${WORKSPACE})
                    script {
                        if ( action == 'deploy' ) {
                            try {
                                sh 'docker login  --username=${registry_user} --password=${registry_pass}   ${registryUrl}'
                                //方法一:
                                //sh 'cp ${Project_name}/target/*.jar ./'
                                //sh 'docker build  -t ${registryUrl}/${Project_name}:${Branch_name}-${BUILD_ID} -f ./Dockerfile_config/${Project_name}/Dockerfile . '
                                //sh 'docker push ${registryUrl}/${Project_name}:${Branch_name}-${BUILD_ID}'
                                //方法二:
                                sh 'cp ${Project_name}/target/*.jar ./ '
                                def app = docker.build('${registryUrl}/${Project_name}:${Branch_name}-${BUILD_ID} -f ./Dockerfile_config/${Project_name}/Dockerfile')
                                app.push('${Branch_name}-${BUILD_ID}')

                                //sh 'docker rmi ${registryUrl}/${Project_name}:${Branch_name}-${BUILD_ID}'
                            } catch (err) {
                                echo 'Build Image failed & End of Pipeline!!!'
                                echo '可能原因:(1)mvn打包子项目失败;(2)上一次失败构建或中断构建项目后,工作目录${WORKSPACE}没有清理(手动执行rm -rf ${WORKSPACE}/*)'
                            }
                        }
                    }
                }
            }
        }
        stage('Deploy to the Target server') {      //部署到目标服务器($action == deploy/restart/rollback)
            steps {
                echo '部署到目标服务器'
                script {
                    timeout(time: 40, unit: 'SECONDS') {    // 设置远程部署超过n秒,将终止该步骤
                        sh 'bash  ./Deploy.sh  ${Project_name}  ${registryUrl}/${Project_name}:${Branch_name}  ${Branch_name}  ${action}  ${BUILD_ID} ${rollback_id}'   //${1,2,3,4,5,6}
                }
            }
        }
        //此步骤在调试Jenkinsfile时可以注释以便了解目录结构
        //亦可以忽略这步骤(有磁盘空间,任性)
        stage('Delete Workspace') {         //清理工作目录(从jenkins上清除刚拉取的代码及mvn编译打包的内容,节省磁盘空间)
            steps {
                echo "清理工作目录: ${WORKSPACE}"
                deleteDir()     //表示删除当前目录(${WORKSPACE})下内容,通常用在构建完毕之后清空工作空间
            }
        }
    }
}

编写各子项目Dockerfile

FROM java:latest
LABEL maintainer="qiujt <qiujt123@163.com>"
ADD canfu-admin/target/canfu-supplier-0.0.1-SNAPSHOT.jar     canfu-supplier.jar
EXPOSE  8096
ENTRYPOINT    ["java","-jar","-Xms512m","-Xmx1024m","-XX:PermSize=512M","-XX:MaxPermSize=1024M","/canfu-supplier.jar"]

编写启动脚本Deploy.sh

#!/bin/bash
#ENV
 #docker私有仓库(Harbor)
  registryUrl=192.168.1.110:5000
  registry_user="xxx"
  registry_pass="xxx"
  project_name=$1
  image_name=$2-${6:-$5}  #$6值缺省值为$5;$6用于回滚)
  env=$3
  action=$4
  build_id=$5
  rollback_id=$6
  node_user=root

  if [ "${env}" == test ];then
    #测试环境
    node1=192.168.1.105
  elif [ "${env}" == master ];then
    #生产环境
    node1=192.168.1.106
  else
    echo '没有${env}环境!!!'
  fi

#Prepare
echo "project_name: $1 , image_name: $2-${6:-$5} , env: $3 , action: $4 , build_id: $5 , rollback_id: $6"
#触发动作
case $action in
deploy | rollback)
  echo "The service is deployed in $node1"
  ssh $node_user@$node1 "docker login --username=${registry_user} --password=${registry_pass} ${registryUrl} && docker pull $image_name && docker rm -f $project_name || true &&  docker  run -itd  --name=$project_name  --restart=always -e TZ="Asia/Shanghai" --net=host  -v /home/dev/logs/$project_name:/data/logs/$project_name   $image_name && docker image prune -a  -f --filter 'until=1h'"
;;

restart)
  echo "The service is restarted in $node1"
  ssh $node_user@$node1 "docker restart ${project_name} && tailf /home/dev/logs/$project_name/${project_name}.log"
;;

*)
  echo 'Please select the correct trigger action:"deploy/rollback/restart"'
;;

esac
docker exec -it jenkins /bin/bash -c 'ssh-keygen -C "root@jenkins"'

(2)然后自行复制jenkins容器的公钥(/root/.ssh/id_rsa.pub)文件内容到目标服务器的/root/.ssh/authorized_keys文件中。
注意第一次连接目标服务器会提示一个交互动作(提示输入“yes”或者“no”继续操作)

[root@tools-env-101 ~]# docker exec -it jenkins /bin/bash -c "ssh 192.168.1.105"
The authenticity of host '192.168.1.105 (192.168.1.105)' can't be established.
ECDSA key fingerprint is SHA256:/2CklRXsExQNpBUr08qN6jqbx6wBkYceC/IShzwAemk.
Are you sure you want to continue connecting (yes/no)?    #提示输入“yes”或者“no”继续操作

要避开这个交互操作有两种方式:
第一种将目标服务器/etc/ssh/ssh_config里面的“StrictHostKeyChecking ask”改为“StrictHostKeyChecking no”,重启ssh服务即可;
第二种直接执行以下命令,交互输入yes即可。

docker exec -it jenkins /bin/bash -c "sed -i '/192.168.1.105/d' /root/.ssh/known_hosts"
docker exec -it jenkins /bin/bash -c "ssh 192.168.1.105"   #输入yes

2、创建jenkins流水线工程




Jenkinsfile

上一篇 下一篇

猜你喜欢

热点阅读