天天看點

Jenkins Generic Webhook 實踐優化 擷取送出資訊

之前gitlab和Jenkins已經內建好了,現在需要來解析一些資料,因為送出建構需要有些值去拿的。

Jenkins Generic Webhook 實踐優化 擷取送出資訊
Jenkins Generic Webhook 實踐優化 擷取送出資訊
Jenkins Generic Webhook 實踐優化 擷取送出資訊

 比如可以擷取誰送出的,哪個分支送出的,使用者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 any

    stages {
        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 Generic Webhook 實踐優化 擷取送出資訊

一個動态傳遞分支參數的示例: 

首先,Jenkins觸發器中配置一個request參數,

runOpts

作為建構類型判斷。

Jenkins Generic Webhook 實踐優化 擷取送出資訊

 第二步, Gitlab webhook中指定此參數。

Jenkins Generic 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 = "[email protected]"
    currentBuild.description ="Trigger by 手動觸發 \n branch: ${env.branchName}"

}
           

try

 語句塊中的是解析Gitlab傳遞過來的資料的,然後将

checkout

 中的分支字元串和倉庫位址使用變量替換。

branchName

 和

srcUrl

 都是解析的Gitlab hook資料。

添加

try

 語句塊的目的也是為了忽略這些錯誤的, 因為手動觸發是拿不到gitlab 傳遞的資料的,這是兩種不同的觸發方式是以一定要注意。 是以最後我們在UI定義兩個參數作為手動觸發使用的。

效果:

Jenkins Generic Webhook 實踐優化 擷取送出資訊

繼續閱讀