[TOC]
0x01 Jenkins之K8s集群自动化部署单war包应用 实验目的 描述: 采用Jenkins从Gitlab中拉取测试项目以及代码质量检测,然后进行编译构建并利用K8s集群进行WAR包应用部署实践,最后将生成的制品进行归档到Gitlab的Release之中;
动态配置文件或者脚本:
setting.xml (Maven编译构建配置文件)
HelloWorld.yaml (应用部署资源清单)
options.sh (部署脚本)
前期准备 描述: 假定你已经按照我前面几篇文章中安装好基础环境。
(0) HelloWorld - Tomcat 应用服务器
[TOC]
0x01 Jenkins之K8s集群自动化部署单war包应用 实验目的 描述: 采用Jenkins从Gitlab中拉取测试项目以及代码质量检测,然后进行编译构建并利用K8s集群进行WAR包应用部署实践,最后将生成的制品进行归档到Gitlab的Release之中;
动态配置文件或者脚本:
setting.xml (Maven编译构建配置文件)
HelloWorld.yaml (应用部署资源清单)
options.sh (部署脚本)
前期准备 描述: 假定你已经按照我前面几篇文章中安装好基础环境。
(0) HelloWorld - Tomcat 应用服务器
Step 1.基础镜像拉取于上传到私有仓库中
1 2 3 4 5 6 7 8 9 weiyigeek@weiyigeek-107:~/k8s/sonarqube$ docker tag tomcat:8.5.61-jdk8-corretto harbor.weiyigeek.top/devops/tomcat:8.5.61-jdk8-corretto weiyigeek@weiyigeek-107:~/k8s/sonarqube$ docker push harbor.weiyigeek.top/devops/tomcat:8.5.61-jdk8-corretto The push refers to repository [harbor.weiyigeek.top/devops/tomcat] f13244e4918b: Pushed 536f15f78828: Pushed 1c98b6d16fad: Pushed fdef502bf282: Pushed cee8d35c645b: Pushed 8.5.61-jdk8-corretto: digest: sha256:110d7391739e868daf8c1bdd03fcb7ffe9eaf2b134768b9162e2cd47d58f7255 size: 1368
Step 2.资源清单文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 cat > HelloWorld.yaml <<'END' apiVersion: v1 kind: Service metadata: name: deploy-maven-svc spec: type: NodePort selector: app: java-maven release: stabel ports: - name: http port: 8080 targetPort: 8080 nodePort: 30089 --- apiVersion: apps/v1 kind: StatefulSet metadata: name: deploy-java-maven spec: serviceName: "deploy-maven-svc" replicas: 3 selector: matchLabels: app: java-maven release: stabel template: metadata: labels: app: java-maven release: stabel spec: volumes: - name: webapps hostPath: type: DirectoryOrCreate path: /nfsdisk-31/test/ - name: timezone hostPath: path: /usr/share/zoneinfo/Asia/Shanghai containers: - name: java-maven image: harbor.weiyigeek.top/devops/tomcat:8.5.61-jdk8-corretto imagePullPolicy: IfNotPresent command: ["bash","-c","cp /tmp/${APPNAME} /usr/local/tomcat/webapps/ROOT.war && catalina.sh run"] env: - name: APPNAME value: HelloWorld-v1.40.war ports: - name: http containerPort: 8080 volumeMounts: - name: webapps mountPath: /tmp/ - name: logs mountPath: /usr/local/tomcat/logs - name: timezone mountPath: /usr/share/zoneinfo/Asia/Shanghai volumeClaimTemplates: - metadata: name: logs spec: accessModes: [ "ReadWriteOnce" ] storageClassName: managed-nfs-storage resources: requests: storage: 1 Gi END
(1) Nginx - Web服务器
(2) Jenkins Pipeline 脚本 Jenkins 流水线脚本如下:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 def PRJECT = "ssh://git@weiyigeek.top/blog.git" def PUBKEY = "5e2f46d9-6725-4399-847f-dafb3f29d0ce" def getSSH() { def remote = [:] remote.name = "K8S#${DEPLOY_HOST}" remote.user = "${DEPLOY_USER}" remote.host = "${DEPLOY_HOST}" remote.port = 20211 remote.allowAnyHosts = true withCredentials([string(credentialsId: "${DEPLOY_CREDENTIALSID}" , variable: 'sshpassword' )]) { remote.password = sshpassword } return remote } def getSecure(Ticket_Token) { def token = "" withCredentials([string(credentialsId: Ticket_Token, variable: 'secure_token' )]) { token = secure_token } println token return token } pipeline { agent { kubernetes { cloud 'kubernetes' namespace 'devops' inheritFrom 'jenkins-slave' workingDir '/home/jenkins/agent' yaml """\ apiVersion: kind: Pod metadata: labels: jenkins: "slave" jenkins/label: 'k8s-slave' spec: containers: - name: 'jnlp' image: 'harbor.weiyigeek.top/devops/jenkins-jnlp:3.13.6-alpine' imagePullPolicy: 'IfNotPresent' command: ["/bin/sh","-c","/usr/local/bin/jenkins-agent.sh && cat"] tty: true volumeMounts: - mountPath: "/home/jenkins/.m2" name: "volume-0" - mountPath: "/var/run/docker.sock" name: "volume-1" """ .stripIndent() } } options { gitLabConnection('Gitlab-weiyigeek' ) gitlabBuilds(builds: ['代码拉取' , '代码检测' , '项目构建' ,'项目部署' ,'成品归档' ,'消息通知' ]) timeout(time: 30 , unit: 'MINUTES' ) } triggers { gitlab( triggerOnPush: false , triggerOnMergeRequest: true , triggerOpenMergeRequestOnPush: "never" , noteRegex: "jenkins build" , branchFilterType: 'All' ) } parameters { string(name: 'RELEASE_VERSION' , defaultValue: "master" , description: 'Message: 请选择部署的Tags版本?' ,trim: 'True' ) choice(name: 'PREJECT_OPERATION' , choices: ['deploy' , 'rollback' , 'redeploy' ], description: 'Message: 选择项目操作方式?' ) choice(name: 'SONARQUBE' , choices: ['False' ,'True' ],description: 'Message: 是否进行代码质量检测?' ) choice(name: 'GITLAB_RELEASE' , choices: ['False' ,'True' ],description: 'Message: 是否进行编译成品发布到Gitlab开发项目Release中?' ) } environment { GITLAB_URL = 'ssh://git@gitlab.weiyigeek.top:2222/weiyigeek/helloworld.git' GITLAB_PROJECTID = '45' GITLAB_PUB = '5e2f46d9-6725-4399-847f-dafb3f29d0ce' GITLAB_TOKEN = 'ce228573-ad3d-40e8-a3bf-b9de510080db' GITLAB_REL = "http://gitlab.weiyigeek.top/api/v4/projects/${GITLAB_PROJECTID}/releases" GITLAB_DOWNLOAD = "http://192.168.12.107:30003/${JOB_NAME}/${APP_NAME}" APP_NAME = "${JOB_NAME}-${RELEASE_VERSION}${APP_SUFFIX}" APP_SUFFIX = ".war" APP_FILE = 'target/*.war' APP_DIR = '/nfsdisk-31/test/' K8S_NAMESPACE = "default" K8S_SELECTOR = "app=java-maven" KS8_ADDRESS = "http://192.168.12.107:30089" def SERVER = '' DEPLOY_CREDENTIALSID = "b846141f-55c2-4b46-98a7-29b9e76af3cc" DEPLOY_HOST = "192.168.12.107" DEPLOY_USER = "root" DEPLOY_PORT = 20211 SONARQUBE_CREDENTIALSID = "18d24c8f-9772-4b3e-934c-f80ed0e96cde" SONARQUBE_PROJECTKEY = "${JOB_NAME}" SONARQUBE_TIMEOUT = '10' ; QYWX_WEBHOOK = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7d7f46fa-28c6-40b3-9c45-de243ec51150' } stages { stage ('代码拉取' ) { steps { timeout(time: 5 , unit: 'MINUTES' ) { script { try { withCredentials([ sshUserPrivateKey(credentialsId: '1d4e61cb-5d59-4da8-813b-a5fb345770c9' , keyFileVariable: 'keyFile' , passphraseVariable: 'pass' , usernameVariable: 'user' ), string(credentialsId: '79a78423-e539-4b1f-a872-f0cf1dd3f9fa' , variable: 'keyPub' ) ]) { writeFile file: 'private.key' , text: keyFile sh "cp \$(cat private.key) ~/.ssh/id_ed25519" writeFile file: 'private.pub' , text: keyPub sh "echo \$(cat private.pub) | base64 -d > ~/.ssh/id_ed25519.pub" } checkout([$class: 'GitSCM' , branches: [[name: "${params.RELEASE_VERSION}" ]], doGenerateSubmoduleConfigurations: false , extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: "${env.GITLAB_PUB}" , url: "${env.GITLAB_URL}" ]]]) updateGitlabCommitStatus name: '代码拉取' , state: 'success' } catch (Exception err) { updateGitlabCommitStatus name: '代码拉取' , state: 'failed' echo err.toString() error "[-Error] : 代码拉取失败\n [-Msg] : ${err.getMessage()} " } echo "[-Info] : RELEASE_VERSION: ${params.RELEASE_VERSION} , PREJECT_OPERATION: ${params.PREJECT_OPERATION}, SONARQUBE: ${params.SONARQUBE}, GITLAB_RELEASE: ${params.GITLAB_RELEASE}" } } } } stage ('代码检测' ) { when { expression { return params.PREJECT_OPERATION != "rollback" } anyOf { environment name: 'SONARQUBE' , value: 'True' } } steps { script { def sonarqubeScanner = tool 'Sonar-Scanner' ; withSonarQubeEnv(credentialsId: "${SONARQUBE_CREDENTIALSID}" ) { sh "${sonarqubeScanner}/bin/sonar-scanner " + "-Dsonar.projectName=${JOB_NAME} " + "-Dsonar.projectKey=${SONARQUBE_PROJECTKEY} " + "-Dsonar.projectVersion=${RELEASE_VERSION} " + "-Dsonar.sourceEncoding=utf8 " + "-Dsonar.sources=. " + "-Dsonar.language=java " + "-Dsonar.java.binaries=." sleep time: "${SONARQUBE_TIMEOUT}" , unit: 'SECONDS' } try { timeout(time: 1 , unit: 'MINUTES' ) { waitForQualityGate abortPipeline: true } updateGitlabCommitStatus name: '代码检测' , state: 'success' } catch (Exception err) { updateGitlabCommitStatus name: '代码检测' , state: 'failed' unstable '代码检测失败' } } } } stage ("项目构建" ) { when { expression { return params.PREJECT_OPERATION != "rollback" } } steps { script { try { sh script: "curl -s -o settings.xml http://gitlab.weiyigeek.top/weiyigeek/helloworld/-/raw/master/settings.xml" sh script: '/usr/local/maven/bin/mvn -s "settings.xml" clean install -Dmaven.test.skip=true' updateGitlabCommitStatus name: '项目构建' , state: 'success' } catch (Exception err) { updateGitlabCommitStatus name: '项目构建' , state: 'failed' unstable '项目构建失败' } } } } stage ("项目部署" ) { steps { script { SERVER = getSSH() try { sh script: """\ curl -s http://gitlab.weiyigeek.top/weiyigeek/helloworld/-/raw/master/${JOB_NAME}.yaml | sed s#__APPNAME__#${APP_NAME}#g > ./${JOB_NAME}.yaml && \ wget http://gitlab.weiyigeek.top/weiyigeek/helloworld/-/raw/master/options.sh -O options.sh """ sshPut remote: SERVER, from: "./${JOB_NAME}.yaml" , into: "${APP_DIR}${JOB_NAME}.yaml" sh script: "chmod +x options.sh && sh -x ./options.sh" updateGitlabCommitStatus name: '测试部署' , state: 'success' }catch (Exception err) { updateGitlabCommitStatus name: '测试部署' , state: 'failed' unstable '部署失败' error "[-Error] : 项目部署失败 \n[-Msg] : ${err.getMessage()} " } } } } stage('成品归档' ) { when { expression { return params.PREJECT_OPERATION != "rollback" && params.GITLAB_RELEASE } } steps { script { if ( ! params.RELEASE_VERSION.contains("master" ) ) { try { archiveArtifacts artifacts: "${APP_FILE}" , onlyIfSuccessful: true def gitlab_token = getSecure("${GITLAB_TOKEN}" ) def gitlab_release = sh(returnStatus: true , script: "sudo apk add jq && curl -s --header 'PRIVATE-TOKEN: ${gitlab_token}' ${GITLAB_REL} | jq .[].tag_name | grep -c '${params.RELEASE_VERSION}'" ) def gitlab_release_dir = "/nfsdisk-31/release/${JOB_NAME}/" echo gitlab_token + " --- " + gitlab_release + "=====" + gitlab_release_dir + "---" if ( gitlab_release != 0 ) { sshCommand remote: SERVER, command: "mkdir -p ${gitlab_release_dir}" sshPut remote: SERVER, from: "./${APP_NAME}" ,into: "${gitlab_release_dir}${APP_NAME}" sh script: """ /usr/local/bin/release-cli --server-url "http://gitlab.weiyigeek.top" --private-token "${gitlab_token}" \ --project-id ${GITLAB_PROJECTID} create \ --name "${JOB_NAME}-${params.RELEASE_VERSION}" \ --tag-name "${params.RELEASE_VERSION}" \ --description "此 ${JOB_NAME} 项目 ${params.RELEASE_VERSION}版本 来自 Jenkins Build 编译构建上传。" \ --assets-link '{"name": "${APP_NAME}","url":"${GITLAB_DOWNLOAD}","link_type":"other"}' """ } else { echo "[-Tips] : Gitlab Release 中已存在 ${params.GITLAB_RELEASE} 版本, 将不会提交该Release到Gitlab中" } updateGitlabCommitStatus name: '成品归档' , state: 'success' } catch (Exception err) { updateGitlabCommitStatus name: '成品归档' , state: 'failed' echo err.toString() } } else { echo "# 版本不能为 ${param.RELEASE_VERSION} , 将不会进行归档!" } } } } } post { always { script { def GIT_COMMIT=sh returnStdout: true , script: "git show --oneline --ignore-all-space --text | head -n 1" qyWechatNotification aboutSend: true , failNotify: true , failSend: true , mentionedMobile: '' , startBuild: true , successSend: true , unstableSend: true , webhookUrl: "${env.QYWX_WEBHOOK}" sh """\ curl -s ${env.QYWX_WEBHOOK} \ -H 'Content-Type: application/json' \ -d ' { "msgtype": "text", "text": { "content": "项目: ${env.SONARQUBE_PROJECTKEY}, 版本: ${params.RELEASE_VERSION}, 操作: ${params.PREJECT_OPERATION} , 信息: ${GIT_COMMIT}, Gitlab-Release 发布: ${params.GITLAB_RELEASE}, 部署地址: ${env.KS8_ADDRESS}" } }' """ } deleteDir() } success { echo '[-Info] : I succeeeded! - 任务成功' updateGitlabCommitStatus name: '消息通知' , state: 'success' } unstable { echo '[-Info] : I am unstable - 不稳定 :/' } failure { echo '[-Info] : I failed - 任务失败 :( ' updateGitlabCommitStatus name: '消息通知' , state: 'failed' } changed { echo '[-Info] : Things were different before - 与以前的情况不一样...' } } }
(3) Shell 部署脚本 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 #!/bin/sh export K8sMaster="${DEPLOY_USER} @${DEPLOY_HOST} " export AppName="${APP_FILE##*/} " export FindAppName=$(find ${WORKSPACE} -maxdepth 2 -type f -name ${AppName} )if [${PREJECT_OPERATION} != "rollback" ];then if [ "${FindAppName} " != "" ]; then echo "[-Msg]: ${FindAppName} ./${APP_NAME} Copying...." cp -rf ${FindAppName} ./${APP_NAME} else echo "[-Error]: FindAppName param error!" exit 1 fi fi function judge () { export ExistResult=$(ssh -p ${DEPLOY_PORT} ${K8sMaster} "ls ${APP_DIR} | grep ${RELEASE_VERSION} | wc -l" ) } function deploy () { if [[ ${ExistResult} -eq 0 || "${RELEASE_VERSION} " == "master" ]];then scp -P ${DEPLOY_PORT} "${APP_NAME} " ${K8sMaster} :${APP_DIR} ${APP_NAME} else echo "[-Msg]: /${APP_NAME} current Deploy....." fi if [[ "${RELEASE_VERSION} " == "master" ]];then ssh -p ${DEPLOY_PORT} ${K8sMaster} "kubectl -n ${K8S_NAMESPACE} delete pod -l ${K8S_SELECTOR} " else ssh -p ${DEPLOY_PORT} ${K8sMaster} "kubectl apply -f ${APP_DIR} ${JOB_NAME} .yaml" fi } function rollback () { if [[ ${ExistResult} -ne 0 ]];then ssh -p ${DEPLOY_PORT} ${K8sMaster} "kubectl apply -f ${APP_DIR} ${JOB_NAME} .yaml" else echo "[-Eroor]: /${APP_NAME} version not exsit....." exit 1 fi } function redeploy () { if [[ "v${GIT_COMMIT} " = "v${GIT_PREVIOUS_SUCCESSFUL_COMMIT} " || ${ExistResult} -gt 0 ]];then echo -e "[-Message]: ${RELEASE_VERSION} Version Exsit !" ssh -p ${DEPLOY_PORT} ${K8sMaster} "find ${APP_DIR} -d -maxdepth 1 -type f -name ${APP_NAME} " scp -P ${DEPLOY_PORT} "${APP_NAME} " ${K8sMaster} :${APP_DIR} ${APP_NAME} fi deploy } judge case ${PREJECT_OPERATION} in "deploy" ) echo "1.deploy" deploy ;; "rollback" ) echo "2.rollback" rollback ;; "redeploy" ) echo "3.redeploy" redeploy ;; *) echo "[-Error] : ${PREJECT_OPERATION} Param Error not in deploy/rollback/redeploy !" exit 1 ;; esac
(4) 效果预览
Step 1.在BlueOcean
进行构建部署参数选择。 描述: 我们可以进行初次部署回滚以及重新构建部署,还包括代码质量检测以及成品自动归档的选择控制。
weiyigeek.top-BlueOcean部署
Step 2.在K8s集群中进行查看Pod迭代变化。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 /nfsdisk-31/test
weiyigeek.top-实验效果