提交流水線
當Gitlab中觸發push操作,則觸發相對應的Jenkins流水線構建。實現快速反饋與驗證。
方式1: 使用Gitlab CI,當有push請求,在CI腳本中遠程觸發Jenkins項目構建。
需要准備Gitlab runner
編寫觸發Jenkins腳
方式2: 使用Gitlab WebHook,當有push請求,直接觸發jenkins項目構建。【采用】
需要配置Gitlab webHook
需要配置Jenkins項目Hook
推薦使用Generic Webhook Trigger觸發器,需要安裝插件
1)安裝插件

2)開啟Generic Webhook Trigger
添加一個請求參數runOpts Request parameters ,用於辨別手動觸發構建與提交構建
配置一個token默認我使用的是項目的名稱,必須唯一,否則在配置了相同的token的項目都會被觸發
Print post content用於展示請求日志,Print contributed variables展示我們在post中獲取的變量內容

3)配置gitlab
我們找到要配置提交觸發構建的項目,設置->集成,勾選Push Events

配置完成,這時候我們進行提交代碼,會發現已經能夠正常觸發項目構建了。如果出現了問題,我們重點檢查jenkins的項目觸發URL和網絡權限問題
二)提交流水線優化
1)分支名稱自動替換、增加構建描述信息
當我們在任意分支提交的時候,Jenkins需要獲取我們提交的分支進行構建,而不是固定的分支
增加獲取hook參數

編寫sharelibrary中的Jenkinsfile文件
if ("${runOpts}" == "GitlabPush"){
env.runOpts = "GitlabPush"
branchName = branchName - "refs/heads/"
currentBuild.description = "Trigger by ${userName} ${branch}"
}
測試

2)變更commit狀態
如何添加這個憑據?
操作方法: 1. 在Gitlab中新建一個token, 系統設置 -> access token 2. 在Jenkins 新建憑據 -> 選擇憑據類型secure text -> 填寫憑據id(可以自定義)-> 填寫gitlab的token。


https://docs.gitlab.com/ee/api/commits.html#post-the-build-status-to-a-commit
關於gitlab中pipeline的狀態有:[pending, running, success, failed, canceled] 。 接口地址為projects/${projectId}/statuses/${commitSha}?state=state

s
共享庫創建一個文件src/org/devops/gitlab.groovy
package org.devops
//封裝HTTP請求
def HttpReq(reqType,reqUrl,reqBody){
def gitServer = "http://gitlab.aa.com/api/v4"
withCredentials([string(credentialsId: 'gitlab-token', variable: 'gitlabToken')]) {
result = httpRequest customHeaders: [[maskValue: true, name: 'PRIVATE-TOKEN', value: "${gitlabToken}"]],
httpMode: reqType,
contentType: "APPLICATION_JSON",
consoleLogResponseBody: true,
ignoreSslErrors: true,
requestBody: reqBody,
url: "${gitServer}/${reqUrl}"
//quiet: true
}
return result
}
//更改提交狀態
def ChangeCommitStatus(projectId,commitSha,status){
commitApi = "projects/${projectId}/statuses/${commitSha}?state=${status}"
response = HttpReq('POST',commitApi,'')
println(response)
return response
}
配置jenkinsfile文件
def gitlab = new org.devops.gitlab()
if ("${runOpts}" == "GitlabPush"){
env.runOpts = "GitlabPush"
branchName = branch - "refs/heads/"
currentBuild.description = "Trigger by ${userName} ${branch}"
gitlab.ChangeCommitStatus(projectId,commitSha,"running")
}
post {
always{
script{
println("always")
}
}
success{
script{
println("success")
gitlab.ChangeCommitStatus(projectId,commitSha,"success")
}
}
failure{
script{
println("failure")
gitlab.ChangeCommitStatus(projectId,commitSha,"failed")
}
}
aborted{
script{
println("aborted")
gitlab.ChangeCommitStatus(projectId,commitSha,"canceled")
}
}
}
}
測試

3)過濾特殊push請求,指定分支push觸發構建
添加三個變量,獲取當前的提交信息 $object_kind $before $after

Expression: ^push\s(?!0{40}).{40}\s(?!0{40}).{40}\srefs/heads/(dev|test|beta)$
Text: $object_kind $before $after $branch

4)合並流水線
關於合並流水線的配置之前要把提交流水線配置好,當提交流水線配置好了,合並流水線只需要修改一個配置。
當流水線成功后才可以合並:會檢查原分支中的最后一次提交的狀態是否為success

當原分支最后一次提交的狀態為success,則可以合並,只有流水線成功后,才可以合並代碼
5)構建失敗郵件通知
安裝插件

首先要為每個開發人員分配一個郵箱,並且要在Gitlab中填寫好。登錄個人用戶進行配置哦

郵件通知的功能很重要,我們要為每條流水線都加上這個步驟,我們在共享庫中封裝一個toemail.groovy。 新建文件src/org/devops/toemail.groovy。在這個文件中,我們寫了一段HTML代碼,主要展示Jenkins的構建信息
package org.devops
//定義郵件內容
def Email(status,emailUser){
emailext body: """
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0">
<img src="http://192.168.1.200:8080/static/0eef74bf/images/headshot.png">
<table width="95%" cellpadding="0" cellspacing="0" style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">
<tr>
<td><br />
<b><font color="#0B610B">構建信息</font></b>
</td>
</tr>
<tr>
<td>
<ul>
<li>項目名稱:${JOB_NAME}</li>
<li>構建編號:${BUILD_ID}</li>
<li>構建狀態: ${status} </li>
<li>項目地址:<a href="${BUILD_URL}">${BUILD_URL}</a></li>
<li>構建日志:<a href="${BUILD_URL}console">${BUILD_URL}console</a></li>
</ul>
</td>
</tr>
<tr>
</table>
</body>
</html> """,
subject: "Jenkins-${JOB_NAME}項目構建信息 ",
to: emailUser
}
Jenkins需要配置郵件通知,安裝插件Email Extension,然后進入系統管理-> 系統設置 ->Extended E-email Notification。
這里我使用的是163郵箱,填寫SMTP服務器地址smtp.163.com 和端口 465注意要開啟SSL,密碼為授權碼。

在流水線中引用
def toemail = new org.devops.toemail()
success{
script{
println("success")
gitlab.ChangeCommitStatus(projectId,commitSha,"success")
toemail.Email("流水線構建成功",userEmail)
}
}
failure{
script{
println("failure")
gitlab.ChangeCommitStatus(projectId,commitSha,"failed")
toemail.Email("流水線構建失敗",userEmail)
}
}
