天天看點

jenkins同一項目多個伺服器,Jenkins流水線--部署多子產品maven項目(推薦)

jenkins同一項目多個伺服器,Jenkins流水線--部署多子產品maven項目(推薦)

最終Jenkins流水線各步驟分解

Jenkins+Springboot+gitlab+maven+jdk+docker

目錄

編寫Jenkinsfile,Dockerfile,Deploy.sh

建立jenkins流水線工程

多子產品maven項目結構大概如下:

cfw-project #父工程

-canfu-eureka #子工程(1)

-canfu-provider #子工程(2)

-canfu-supplier #子工程(n)

-src

-pom.xml

-pom.xml

-Dockerfile_config #存放各子工程Dockerfile

-Deploy.sh #遠端部署腳本

jenkins同一項目多個伺服器,Jenkins流水線--部署多子產品maven項目(推薦)

1、編寫Jenkinsfile,Dockerfile,Deploy.sh

編寫聲明式Jenkinsfile

步驟大概為:(1)列印變量資訊;(2)從源碼庫拉取對應分支代碼到"${WORKSPACE}";(3)maven編譯、打包;(4)将jar包建構成docker鏡像;(5)觸發部署腳本(Deploy.sh )實施遠端部署/重新開機/復原;(6)清理工作目錄

pipeline {

agent any

environment {

registryUrl= "192.168.1.110:5000" //搭建docker私有倉庫(Harbor)或者 用DockerHub 又或者用雲平台的“容器鏡像服務”

registry_user= "xxx"

registry_pass= "xxx"

}

options {

timestamps() //設定在項目列印日志時帶上對應時間

disableConcurrentBuilds() //不允許同時執行流水線,被用來防止同時通路共享資源等

timeout(time: 5, unit: 'MINUTES') // 設定流水線運作超過n分鐘,Jenkins将中止流水線

buildDiscarder(logRotator(numToKeepStr: '20')) // 表示保留n次建構曆史

}

//gitlab webhook觸發器

//聚合項目,代碼發生以下動作後,所有子項目将被觸發建構,可選擇使用(前提需要gitlab配置 webhook)

//triggers{ //方法一,為All時

// gitlab( triggerOnPush: true, //代碼有push動作就會觸發job

// triggerOnMergeRequest: true, //代碼有merge動作就會觸發job

// branchFilterType: "All") //為All時(隻有符合條件的分支才會觸發建構 “All/NameBasedFilter/RegexBasedFilter”)

//}

//triggers{ //方法二,為branchFilterType時

// gitlab( triggerOnPush: true,

// triggerOnMergeRequest: true,

// branchFilterType: "branchFilterType", //為branchFilterType時

// includeBranchesSpec: "dev") //基于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}"

}

}

//此步驟在調試Jenkinsfile時可以注釋以便了解目錄結構

stage('Delete Workspace') { //清理工作目錄

steps {

echo "清理工作目錄: ${WORKSPACE}"

deleteDir() //表示删除目前目錄(${WORKSPACE})下内容,通常用在建構完畢之後清空工作空間

}

}

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' ) {

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配置檔案打包)

}

}

}

}

stage('Build & Push Image to Harbor') { //建構,推送鏡像

steps {

echo '建構,推送鏡像到docker鏡像倉庫'

dir ('./') { //指定工作目錄(預設為${WORKSPACE})

script {

if ( action == 'deploy' ) {

//方法一:

//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 'docker login --username=${registry_user} --password=${registry_pass} ${registryUrl}'

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}'

}

}

}

}

}

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}

}

}

}

}

}

編寫各子項目Dockerfile

FROM java:latest

LABEL maintainer="qiujt "

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"]

FROM 指定基礎鏡像,并且必須是第一條指令。(可以選擇更小的鏡像openjdk:8-jdk-alpine,不過一些背景項目驗證碼圖檔會出不來,慎用)

LABEL MAINTAINER 指定維護者資訊 文法:LABEL maintainer=" user_name "

ADD 将主控端目錄下的檔案拷貝進鏡像且 ADD 指令會自動處理 URL 和解壓 tar 壓縮包

EXPOSE 目前容器對外暴露出的端口

ENTRYPOINT:指定一個容器啟動時要運作的指令,ENTRYPOINT 的目的和 CMD 一樣,都是在指定容器啟動程式及參數

編寫啟動腳本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 [email protected]$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 [email protected]$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 login:登入docker私有倉庫

docker pull && docker rm:伺服器拉取對應鏡像;判斷容器是否存在,如果存在就結束容器,否則跳過

docker run:基于鏡像建立容器。

--restart=always:當 Docker程序重新開機後,容器自動啟動;

--net=host:指定容器網絡模式為host,即容器暴露的端口,主控端就是什麼端口;

-e TZ="Asia/Shanghai" :定義容器使用時區;

-v:将子項目日志目錄從容器裡映射到主控端(視個人項目情況變更)。

docker image prune:删除1小時前拉取的、并且未被使用的鏡像

補充:由于定義的Jenkinsfile部署階段需要在目标伺服器(例如:192.168.1.105)上執行操作,是以需要配置通過ssh連接配接。

(1)首先需要在Jenkins容器裡面生成ssh的公鑰密鑰;

docker exec -it jenkins /bin/bash -c 'ssh-keygen -C "[email protected]"'

(2)然後複制jenkins容器的公鑰(/root/.ssh/id_rsa.pub)檔案内容到目标伺服器的/root/.ssh/authorized_keys檔案中(使用ssh-copy-id指令)。

注意第一次連接配接目标伺服器會提示一個互動動作(提示輸入“yes”或者“no”)

[[email protected] ~]# docker exec -it jenkins /bin/bash -c "ssh-copy-id 192.168.1.105"

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"

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 #提示互動動作,此處輸入“yes”繼續操作

/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys

[email protected]'s password: #輸入目标伺服器ssh使用者登入密碼(預設使用者root)

Number of key(s) added: 1

Now try logging into the machine, with: "ssh '192.168.1.105'"

and check to make sure that only the key(s) you wanted were added.

[[email protected] ~]# docker exec -it jenkins /bin/bash -c "ssh 192.168.1.105" #成功免密登入目标伺服器

Last login: Wed Nov 18 12:11:38 2020 from 192.168.1.186

[[email protected] ~]#

( 要避開上面提到的互動動作(輸入“yes”或者“no”),還有下面一種方法:

将目标伺服器/etc/ssh/ssh_config裡面的“StrictHostKeyChecking ask”改為“StrictHostKeyChecking no”,重新開機ssh服務即可。

2、建立jenkins流水線工程

jenkins同一項目多個伺服器,Jenkins流水線--部署多子產品maven項目(推薦)
jenkins同一項目多個伺服器,Jenkins流水線--部署多子產品maven項目(推薦)

配置選項參數01

jenkins同一項目多個伺服器,Jenkins流水線--部署多子產品maven項目(推薦)

配置選項參數02

jenkins同一項目多個伺服器,Jenkins流水線--部署多子產品maven項目(推薦)

放置Jenkinsfile

jenkins同一項目多個伺服器,Jenkins流水線--部署多子產品maven項目(推薦)

選擇參數觸發建構

jenkins同一項目多個伺服器,Jenkins流水線--部署多子產品maven項目(推薦)

成功建構,檢視記錄檔