目錄一覽:
0x01 基礎實踐
-
(1) Maven 構建之 Pipeline Script
-
(2) Maven 構建之 Pipeline Script from SCM
-
(3) Jenkins pipeline 之 郵件(Email)發信管理
WeiyiGeek Blog - 為了能到遠方,腳下的每一步都不能少。
原文地址: https://mp.weixin.qq.com/s/RES8eg0ljzdrQ_ls_hHWjw
Tips : 本文章來源 Blog 站點或者 WeiyiGeek
公眾賬號 (技術交流、友鏈交換請郵我喲
),
- 微信公眾號-WeiyiGeek # 精華文章發布地址(及時發布)
- 首頁-https://weiyigeek.top # 國內有時訪問較慢(及時更新)
- 博客-https://blog.weiyigeek.top # 國內訪問快但(更新不及時)
實現效果:
0x01 基礎實踐
(1) Maven 構建之 Pipeline Script
描述:此處重新不在累述新建流水線任務(maven-pipeline-helloword
)而是直接進行配置測試等關鍵項;
流程:代碼拉取 -> 代碼檢測 -> 代碼構建 -> 代碼部署 -> 消息通知
Step 1. Dashboard -> maven-pipeline-helloword -> 流水線項目配置 (名稱|丟棄舊的構建|參數化構建過程(Git/名稱))
# Git 參數
名稱: git_tags
描述: Project_Release
參數類型: 標簽
默認值: origin/master
排序方式: DESCENDING SMART
----------------------------
# 選項 參數
名稱: deploy_option
選項:
deploy
rollback
redeploy
描述: 部署&回退&重部署
-
Step 2.流水線 Pipeline script 編寫
pipeline {
agent any
stages {
stage ("代碼獲取") {
steps {
checkout([$class: 'GitSCM', branches: [[name: '${git_tags}']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'b4c8b4e9-2777-44a1-a1ed-e9dc21d37f4f', url: 'git@gitlab.weiyigeek.top:ci-cd/java-maven.git']]])
}
}
stage ("代碼質檢") {
steps {
sh label: 'sonar', returnStatus: true, script: '''/usr/local/bin/sonar-scanner -Dsonar.projectName=${JOB_NAME} -Dsonar.projectKey=Hello-World -Dsonar.sources=.'''
}
}
stage ("項目構建") {
steps {
// 此處實際上不用執行cd命令
sh label: 'build', script: 'cd /var/lib/jenkins/workspace/maven-pipeline-helloword/ && /usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true '
}
}
stage ("項目部署") {
steps {
// 腳本為前面一章的部署腳本(兩種方式)
sh label: 'deploy', script: '/tmp/script/maven-jenkins-ci-script.sh'
// sh "/tmp/script/maven-jenkins-ci-script.sh"
}
}
}
// 消息通知: POST階段當所有任務執行后觸發
post {
// 企業微信
always {
qyWechatNotification aboutSend: true, failNotify: true, failSend: true, mentionedId: 'ALL', mentionedMobile: '', startBuild: true, successSend: true, unstableSend: true, webhookUrl: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c222f3fc-f645-440a-ad24-0ce8d9626fa0'
}
// 釘釘
success {
//當此Pipeline成功時打印消息(注意此處的robot為您在Jenkins全局配置中設置釘釘的id值)
echo 'success'
dingtalk (
robot: 'weiyigeek-1000',
type: 'LINK',
title: 'Jenkins 持續集成 - 任務名稱 ${JOB_NAME}',
text: [
'項目構建成功',
'Pipeline 流水線測試'
],
messageUrl: 'http://www.weiyigeek.top',
picUrl: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2319834554,1372531032&fm=26&gp=0.jpg',
atAll: true
)
}
}
}
-
Step 3.Pipeline maven-pipeline-helloword 進行選項參數構建 (Build with Parameters)-> 部署 v1.8 版本
-
Step 4.查看部署結果與信息通知
(2) Maven 構建之 Pipeline Script from SCM
描述: 我也可以將上面流水線的腳本放在我們的代碼項目之中,在流水線拉取項目時候便會自動按照項目中的Jenkinsfile
文件內容進行執行對於操作
-
Step 1.修改項目首頁文件以及在項目根添加Jenkinsfile文件(內容將取消第一階段的代碼拉取),例如:
# (1) E:\EclipseProject\hello-world\src\main\webapp\index.jsp
Maven - Hello World - v1.10 - Pipeline script for SCM
# (2) 項目信息
/e/EclipseProject/hello-world (master)
$ ls
Jenkinsfile pom.xml src/ target/
# (3) Jenkinsfile :注意內容將取消第一階段的代碼拉取
pipeline {
agent any
stages {
stage ("代碼質檢") {
steps {
sh label: 'sonar', returnStatus: true, script: '''/usr/local/bin/sonar-scanner -Dsonar.projectName=${JOB_NAME} -Dsonar.projectKey=Hello-World -Dsonar.sources=.'''
}
}
stage ("項目構建") {
steps {
sh label: 'build', script: 'cd /var/lib/jenkins/workspace/maven-pipeline-helloword/ && /usr/local/maven/bin/mvn clean package -Dmaven.test.skip=true '
}
}
stage ("項目部署") {
steps {
// 腳本為前面一章的部署腳本
sh label: 'deploy', script: '/tmp/script/maven-jenkins-ci-script.sh'
}
}
}
// 消息通知: POST階段當所有任務執行后觸發
post {
// 企業微信
always {
qyWechatNotification aboutSend: true, failNotify: true, failSend: true, mentionedId: 'ALL', mentionedMobile: '', startBuild: true, successSend: true, unstableSend: true, webhookUrl: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c222f3fc-f645-440a-ad24-0ce8d9626fa0'
}
// 釘釘
success {
//當此Pipeline成功時打印消息 (注意此處的robot為您在Jenkins全局配置中設置釘釘的id值)
echo 'success'
dingtalk (
robot: 'weiyigeek-1000',
type: 'LINK',
title: 'Jenkins 持續集成 - 任務名稱 ${JOB_NAME}',
text: [
'項目構建成功',
'Pipeline 流水線測試'
],
messageUrl: 'http://www.weiyigeek.top',
picUrl: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2319834554,1372531032&fm=26&gp=0.jpg',
atAll: true
)
}
}
}
-
Step 2.上傳修改的項目到Gitlab內部私有倉庫中
$ git add .
$ git commit -m "v1.10 pipeline script for SCM"
# [master 3f9b6e8] v1.10 pipeline
# 2 files changed, 26 insertions(+), 1 deletion(-)
# create mode 100644 Jenkinsfile
$ git push
# To http://gitlab.weiyigeek.top/ci-cd/java-maven.git
# 0f50b10..3f9b6e8 master -> master
$ git tag -a "v1.10" -m "v1.10 Pipelinescript for SCM "
$ git push origin v1.10
# To http://gitlab.weiyigeek.top/ci-cd/java-maven.git
# * [new tag] v1.10 -> v1.10
-
Step 3.任務項目流水線設置 -> 選擇 Pipeline script from SCM -> git -> 輸入 Repository URL 和 Credentials -> 指定分支
Branches to build
(以及Jenkinsfile 拉取的文件名實現自動構建集成)
-
Step 4.項目構建參數輸入 -> v1.10 | deploy -> 進行構建 -> 查看流水線
-
Step 5.查看部署結果
http://10.10.107.202:30089/
結果正常;
Maven - Hello World - v1.10 - Pipeline script for SCM
訪問時間: Tue Jan 26 2021 14:54:35 GMT+0800 (中國標准時間)
Server : Apache Tomcat/8.5.61 | 10.244.1.217
Client : 10.244.0.0 | 10.244.0.0
Document_Root : /usr/local/tomcat/webapps/ROOT/
URL : 10.10.107.202/index.jsp
(3) Jenkins pipeline 之 郵件(Email)發信管理
描述: 如果利用 Freestyle 的原生Job我們可以很好的進行Job郵件發信,而在與 Jenkins 流水線中需要Extended E-mail Notification
的方式進行實現(此處只是簡單說明建議采用釘釘或者企業微信的方式更加及時方便);
下面提供兩種格式進行參考:
-
(1) Scripted Pipeline
node ("master"){ parameters {string(name:'Jenkins',defaultValue:'Hello',description:'How should I greet the world')} echo "${params.nane} 你好!" // gitlab 流水線通知 gitlabCommitStatus { stage('第1步拉代碼'){ echo "拉代碼" git credentialsId: '03fd8295-c536-4871-9794-1c37394676e0', url: 'git@gitlab.corp.XXX.com:wangxu/ops.git' } stage('第2步編譯'){ echo "編譯" // sh "source /etc/profile && /usr/local/maven/bin/mvn clean compile" } stage('第3步打包'){ echo "打包,有一個mail模塊是系統級別的,需要sudo" // sh "sudo /usr/local/maven/bin/mvn package" // echo "完成后 修改一下權限,否則下一次麻煩" // sh "sudo chown -R jenkins: ." // sh "find -name '*SNAPSHOT.jar' " } stage('第四步單元測試'){ echo "單元測試" //sh "sudo /usr/local/maven/bin/mvn test" } stage("放到下載服務器上"){ echo "發送文件" // sh "sudo cp ./account-email/target/account-email-1.0.0-SNAPSHOT.jar /home/admin/webserver/html/download && sudo chown -R admin: /home/admin/webserver/html/download" } } stage("發送郵件"){ def git_url = 'git@gitlab.corp.XXX.com:wangxu/ops.git' def branch = 'dev' def username = 'Jenkins' echo "Hello Mr.${username}" echo "GIT路徑: ${git_url}" echo "發送郵件" emailext body: """ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>${ENV, var="JOB_NAME"}-第${BUILD_NUMBER}次構建日志</title> </head> <body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0"> <table width="95%" cellpadding="0" cellspacing="0" style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif"> <tr> <td>(本郵件由程序自動下發,請勿回復!)</td> </tr> <tr> <td> <h2><font color="#FF0000">構建結果 - ${BUILD_STATUS}</font></h2> </td> </tr> <tr> <td><br /> <b><font color="#0B610B">構建信息</font></b> <hr size="2" width="100%" align="center" /> </td> </tr> <tr><a href="${PROJECT_URL}">${PROJECT_URL}</a> <td> <ul> <li>項目名稱:${PROJECT_NAME}</li> <li>GIT路徑:<a href="git@gitlab.corp.XXX.com:wangxu/ops.git">git@gitlab.corp.XXX.com:wangxu/ops.git</a></li> <li>GIT分支:master</li> <li>構建編號:${BUILD_NUMBER}</li> <li>觸發原因:${CAUSE}</li> <li>構建日志:<a href="${BUILD_URL}console">${BUILD_URL}console</a></li> </ul> </td> </tr> <tr> <td> <b><font color="#0B610B">變更信息:</font></b> <hr size="2" width="100%" align="center" /> </td> </tr> <tr> <td> <ul> <li>上次構建成功后變化 : ${CHANGES_SINCE_LAST_SUCCESS}</a></li> </ul> </td> </tr> <tr> <td> <ul> <li>上次構建不穩定后變化 : ${CHANGES_SINCE_LAST_UNSTABLE}</a></li> </ul> </td> </tr> <tr> <td> <ul> <li>歷史變更記錄 : <a href="${PROJECT_URL}changes">${PROJECT_URL}changes</a></li> </ul> </td> </tr> <tr> <td> <ul> <li>變更集:${JELLY_SCRIPT,template="html"}</a></li> </ul> </td> </tr> <!-- <tr> <td> <b><font color="#0B610B">Failed Test Results</font></b> <hr size="2" width="100%" align="center" /> </td> </tr> <tr> <td> <pre style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">${FAILED_TESTS}</pre> <br /> </td> </tr> <tr> <td> <b><font color="#0B610B">構建日志 (最后 100行):</font></b> <hr size="2" width="100%" align="center" /> </td> </tr>--> <!-- <tr> <td>Test Logs (if test has ran): <a href="${PROJECT_URL}ws/TestResult/archive_logs/Log-Build-${BUILD_NUMBER}.zip">${PROJECT_URL}/ws/TestResult/archive_logs/Log-Build-${BUILD_NUMBER}.zip</a> <br /> <br /> </td> </tr> --> <!-- <tr> <td> <textarea cols="80" rows="30" readonly="readonly" style="font-family: Courier New">${BUILD_LOG, maxLines=100,escapeHtml=true}</textarea> </td> </tr>--> <hr size="2" width="100%" align="center" /> </table> </body> </html> """, subject: '$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS!', to: 'master@weiyigeek.top' } }
-
(2) Declarative Pipeline
1 pipeline{ 2 agent{label 'master'} 3 environment { 4 git_url = 'git@gitlab.corp.XXX.com:wangxu/ops.git' 5 git_key = '03fd8295-c536-4871-9794-1c37394676e0' 6 git_branch = 'master' 7 } 8 9 stages { 10 stage('下載代碼') { 11 steps { 12 git branch: "${git_branch}",credentialsId: "${git_key}", url: "${env.git_url}" 13 } 14 } 15 } 16 17 post { 18 //always部分 pipeline運行結果為任何狀態都運行 19 always{ 20 script{ 21 emailext body: 22 ''' <!DOCTYPE html> 23 <html> 24 <head> 25 <meta charset="UTF-8"> 26 <title>${ENV, var="JOB_NAME"}-第${BUILD_NUMBER}次構建日志</title> 27 </head> 28 <body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0"> 29 <table width="95%" cellpadding="0" cellspacing="0" style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif"> 30 <tr> 31 <td>(本郵件由程序自動下發,請勿回復!)</td> 32 </tr> 33 <tr> 34 <td> 35 <h2><font color="#FF0000">構建結果 - ${BUILD_STATUS}</font></h2> 36 </td> 37 </tr> 38 <tr> 39 <td><br /> 40 <b><font color="#0B610B">構建信息</font></b> 41 <hr size="2" width="100%" align="center" /> 42 </td> 43 </tr> 44 <tr><a href="${PROJECT_URL}">${PROJECT_URL}</a> 45 <td> 46 <ul> 47 <li>項目名稱:${PROJECT_NAME}</li> 48 <li>GIT路徑:<a href="git@gitlab.corp.XXX.com:wangxu/ops.git">git@gitlab.corp.XXX.com:wangxu/ops.git</a></li> 49 <li>GIT分支:master</li> 50 <li>構建編號:${BUILD_NUMBER}</li> 51 <li>觸發原因:${CAUSE}</li> 52 <li>構建日志:<a href="${BUILD_URL}console">${BUILD_URL}console</a></li> 53 </ul> 54 </td> 55 </tr> 56 <tr> 57 <td> 58 <b><font color="#0B610B">變更信息:</font></b> 59 <hr size="2" width="100%" align="center" /> 60 </td> 61 </tr> 62 <tr> 63 <td> 64 <ul> 65 <li>上次構建成功后變化 : ${CHANGES_SINCE_LAST_SUCCESS}</a></li> 66 </ul> 67 </td> 68 </tr> 69 <tr> 70 <td> 71 <ul> 72 <li>上次構建不穩定后變化 : ${CHANGES_SINCE_LAST_UNSTABLE}</a></li> 73 </ul> 74 </td> 75 </tr> 76 <tr> 77 <td> 78 <ul> 79 <li>歷史變更記錄 : <a href="${PROJECT_URL}changes">${PROJECT_URL}changes</a></li> 80 </ul> 81 </td> 82 </tr> 83 <tr> 84 <td> 85 <ul> 86 <li>變更集:${JELLY_SCRIPT,template="html"}</a></li> 87 </ul> 88 </td> 89 </tr> 90 <!-- 91 <tr> 92 <td> 93 <b><font color="#0B610B">Failed Test Results</font></b> 94 <hr size="2" width="100%" align="center" /> 95 </td> 96 </tr> 97 <tr> 98 <td> 99 <pre style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">$FAILED_TESTS</pre> 100 <br /> 101 </td> 102 </tr> 103 104 <tr> 105 <td> 106 <b><font color="#0B610B">構建日志 (最后 100行):</font></b> 107 <hr size="2" width="100%" align="center" /> 108 </td> 109 </tr>--> 110 <!-- <tr> 111 <td>Test Logs (if test has ran): <a 112 href="${PROJECT_URL}ws/TestResult/archive_logs/Log-Build-${BUILD_NUMBER}.zip">${PROJECT_URL}/ws/TestResult/archive_logs/Log-Build-${BUILD_NUMBER}.zip</a> 113 <br /> 114 <br /> 115 </td> 116 </tr> --> 117 <!-- 118 <tr> 119 <td> 120 <textarea cols="80" rows="30" readonly="readonly" style="font-family: Courier New">${BUILD_LOG, maxLines=100,escapeHtml=true}</textarea> 121 </td> 122 </tr>--> 123 <hr size="2" width="100%" align="center" /> 124 125 </table> 126 127 128 </body> 129 </html> 130 ''', 131 subject: '$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS!', to: 'master@weiyigeek.top' 132 } 133 } 134 135 success { 136 //當此Pipeline成功時打印消息 137 echo 'success' 138 } 139 failure { 140 //當此Pipeline失敗時打印消息 141 echo 'failure' 142 } 143 unstable { 144 //當此Pipeline 為不穩定時打印消息 145 echo 'unstable' 146 } 147 aborted { 148 //當此Pipeline 終止時打印消息 149 echo 'aborted' 150 } 151 changed { 152 //當pipeline的狀態與上一次build狀態不同時打印消息 153 echo 'changed' 154 } 155 } 156 }
WeiyiGeek Blog - 為了能到遠方,腳下的每一步都不能少。
Tips : 本文章來源 Blog 站點或者 WeiyiGeek
公眾賬號 (友鏈交換請郵我喲
):
-
微信公眾號-WeiyiGeek # 精華文章發布地址(及時發布)
-
https://weiyigeek.top 國內有時訪問較慢
-
https://weiyigeek.gitee.io
Tips: 更多學習筆記文章請關注
WeiyiGeek
公眾賬號
【微信公眾號關注(點擊)】
【郵箱聯系: Master#weiyigeek.top】