之前gitlab和Jenkins已经集成好了,现在需要来解析一些数据,因为提交构建需要有些值去拿的。(通过获取post请求当中body当中的数据)
比如可以获取谁提交的,哪个分支提交的,用户Email和commitid。
"user_username": "root"
"ref": "refs/heads/master""user_email": ""
"checkout_sha": "1d6ed28d4536ce9313e57b47a821753333aab1da"
webHookData = readJSON text: "${webHookData}"
userName = webHookData["user_username"]
userEmail = webHookData["user_email"]
branchName = webHookData["ref"] - "refs/heads/"
commitID = webHookData["checkout_sha"]currentBuild.displayName = commitID
currentBuild.description = "Trigger by user ${userName} \n branch: ${branchName}"pipeline {agent anystages {stage('resdJson') {steps {println("the user name is ${userName}")println("the trigger branch name is ${branchName}")println("the user email is ${userEmail}")}}}
}[Pipeline] readJSON
[Pipeline] node
Running on build-01 in /data/cicd/jenkinsagent/workspace/Gitlab-Webhook-Trigger
[Pipeline] {
[Pipeline] stage
[Pipeline] { (resdJson)
[Pipeline] echo
the user name is root
[Pipeline] echo
the trigger branch name is master
[Pipeline] echo
the user email is
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
一个动态传递分支参数的示例
首先,Jenkins触发器中配置一个request参数, runOpts
作为构建类型判断。
第二步, Gitlab webhook中指定此参数。
第三步, 构建测试。
/*
支持自动构建和手动构建:
1. 在触发添加了一个request参数 runOpts
2. Gitlab webhook中添加runOpts参数=gitlab
3. JenkinsPipeline 根据runOpts值进行运行
*///gitlab触发
try {if ( "${runOpts}" == "gitlab"){//自动// 操作webhook数据println("${WebHookData}")webHookData = readJSON text: "${WebHookData}"env.userName = webHookData["user_username"]env.userEmail = webHookData["user_email"]env.branchName = webHookData["ref"] - "refs/heads/"env.srcUrl = webHookData["project"]["git_http_url"]env.commitID = webHookData["checkout_sha"]currentBuild.description = "Trigger by user ${env.userName} \n branch: ${env.branchName}"currentBuild.displayName = env.commitID}
} catch(e){println(e)env.userEmail = "2560350642@qq.com"currentBuild.description ="Trigger by 手动触发 \n branch: ${env.branchName}"}
try
语句块中的是解析Gitlab传递过来的数据的,然后将 checkout
中的分支字符串和仓库地址使用变量替换。 branchName
和 srcUrl
都是解析的Gitlab hook数据。
添加 try
语句块的目的也是为了忽略这些错误的, 因为手动触发是拿不到gitlab 传递的数据的,这是两种不同的触发方式所以一定要注意。 所以最后我们在UI定义两个参数作为手动触发使用的。
效果: