1 Gitlab和Jenkins集成
1.1 基本流程
- 安装Gitlab和Jenkins
- 配置Jenkins服务器的Maven环境
- 配置Gitlab服务器ssh公钥(Jenkins服务器上的id_rsa.pub)
- 配置Jenkins服务器Gitlab凭证(私钥)
- 配置从Github获取pipeline脚本
- 编写pipeline脚本
- 执行pipeline
1.2 pipeline脚本
包括两个阶段,第一个阶段获取Gitlab的代码,Gitlab拉取源码的地址和分支通过srcUrl和branchName参数进行配置,checkout的语法可以在Jenkins中通过可视化界面获取。第二个阶段进行构建,调用共享库中定义的build方法,在执行前指定build的类型和脚本即可。
#!groovy
// sharelibrary
@Library('jenkinslib') _
def build = new org.devops.build()
def deploy = new org.devops.deploy()
def tools = new org.devops.tools()
// env
String buildShell = "${env.buildShell}"
String buildType = "${env.buildType}"
String deployHosts = "${env.deployHosts}"
String srcUrl = "${env.srcUrl}"
String branchName = "${env.branchName}"
pipeline {
agent {
node {
label "master"
}
}
stages {
stage("CheckOut") {
steps {
script {
tools.PrintMes('获取代码', "green")
checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], extensions: [], userRemoteConfigs: [[credentialsId: '1bf507af-c920-41b1-beea-d3b191af9cd4', url: "${srcUrl}"]]])
}
}
}
stage("Build") {
steps {
script {
tools.PrintMes('执行打包', "green")
build.Build(buildType, buildShell)
//deploy.AnsibleDeploy("${deployHosts}", "-m ping")
}
}
}
}
}
其中共享库中的内容为:
// jenkinslib/src/org/devops/build.groovy
def Build(buildType, buildShell) {
def buildTools = ["mvn":"maven3.6.3", "ant":"ANT", "gradle": "GRADLE", "npm": "node"]
buildHome = tool buildTools[buildType]
println("buildHome is ${buildHome}")
sh "${buildHome}/bin/${buildType} ${buildShell}"
}
// jenkinslib/src/org/devops/tools.groovy
//格式化输出
def PrintMes(value,color){
colors = ['red' : "\033[40;31m >>>>>>>>>>>${value}<<<<<<<<<<< \033[0m",
'blue' : "\033[47;34m ${value} \033[0m",
'green' : "[1;32m>>>>>>>>>>${value}>>>>>>>>>>[m",
'green1' : "\033[40;32m >>>>>>>>>>>${value}<<<<<<<<<<< \033[0m" ]
ansiColor('xterm') {
println(colors[color])
}
}
1.3 实验结果
从Github获取pipeline脚本
配置pipeline执行参数
pipeline执行结果
2 配置Gitlab提交流水线
2.1 引入Webhook自动触发流水线
安装Generic Webhook Trigger插件,通过Gitlab的PUSH事件自动触发流水线的执行。
在Jenkins项目中配置
在Gitlab项目中配置
url:http://${jenkins_url}/generic-webhook-trigger/invoke?token=${token}&runOpts=GitlabPush
指定Jenkins的URL和项目的Token
如果报:Url is blocked: Requests to the local network are not allowed的错误,就需要去admin->setting->network,勾选第二项
发起一个PUSH事件测试连接性是否良好,返回HTTP200
同时Jenkins中任务被PUSH事件触发,自动开始执行流水线
执行成功
从hook打印的日志中可以看到
2.2 优化PUSH流水线
2.2.1 分支自动匹配
从上面的实验中可以知道,在webhook url中传入的url参数会被注入到Jenkins的全局变量中。
在Jenkins中配置项目,配置Webhook插件的Post content parameters,用来获取分支名称。
修改Jenkinsfile在拉取代码的时候可以判断分支名
steps {
script {
if("${runOpts}" == "GitlabPush") {
branchName = branch - "refs/heads/"
}
println("${branchName}")
tools.PrintMes('获取代码', "green")
checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], extensions: [], userRemoteConfigs: [[credentialsId: '1bf507af-c920-41b1-beea-d3b191af9cd4', url: "${srcUrl}"]]])
}
}
}
2.2.2 增加构建的描述信息
通过currentBuild.description增加构建的描述信息 在Jenkins项目中添加变量
修改Jenkinsfile
if("${runOpts}" == "GitlabPush") {
branchName = branch - "refs/heads/"
currentBuild.description = "Trigger by ${userName} ${branch}"
}
在执行构建的时候会显示描述信息
2.2.3 变更commit状态
pipeline接口状态:
- pending
- running
- success
- failed
- canceled
接口:GET /projects/:id/repository/commits/:sha/statuses
在Jenkinsfile中添加post请求,先封装一个http请求,然后调用http请求。同时Jenkins需要安装http request插件。如果要向gitlab发起http请求需要在凭证中配置字符串凭证,gitlab-token从gitlab的setting > Access Tokens > Personal Access Tokens中创建。token错误会报401的错。
def HttpReq(reqType,reqUrl,reqBody){
def gitServer = "http://192.168.3.134:17000/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
}
在Jenkins中添加projectId和commitSha两个变量,取值为$.project.id和$.checkout_sha,调用共享库函数修改commit状态。
提交之后在Gitlab中提交修改的项目的commit中可以看到Pipeline执行的状态。
2.2.4 过滤特殊的PUSH请求
创建Post content parameters:object_kind:$.object_kind after:$.after before: $.before
配置过滤的正则表达式和文本
2.2.5 构建邮件通知
3 配置Gitlab合并流水线
目标:当流水线成功后自动合并 配置Gitlab Settings
创建一个Merge Requests
pipeline执行成功之后,才可以点击merge按钮