jenkins pipeline中動態定義變數(流程控制語句)
阿新 • • 發佈:2019-01-10
場景:根據job名稱定義不同的程式碼倉庫地址和分支
方案:使用script把整個程式碼下載過程包含起來
常規寫法是這樣的:
pipeline
{
agent { label 'test' }
stages
{
stage('DownloadCode')
{
steps
{
checkout([
$class: 'GitSCM',
branches: [[name: 'master']],
doGenerateSubmoduleConfigurations: false,
extensions: [
[$class: 'CleanBeforeCheckout'],
[$class: 'RelativeTargetDirectory', relativeTargetDir: 'code'],
[$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', timeout: 3, trackingSubmodules: false]],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: 'xxx',
url: ' [email protected]']]])
}
}
}
}
這種寫法的弊端就是固定寫好程式碼倉庫地址和分支,如果有多個類似的job,只是程式碼倉庫不同,就需要多個Jenkinsfile
設想對於這種多個pipeline,步驟都是相同或相似的,只是程式碼倉庫不同的情況,統一使用一個Jenkinsfile,在Jenkinsfile裡面通過對pipeline的名字判斷來分別定義git url地址和branch等變數
在Jenkinsfile裡面使用switch等語句時需要在script{}裡面,因此所定義的變數在script外面就獲取不到了
嘗試多種方法總會報錯或者在下面下載程式碼時獲取不到前面定義的變數
最終解決方案:
pipeline
{
agent { label 'test' }
stages
{
stage('DownloadCode')
{
steps
{
script
{
//according jenkins job name to set git url and branch to download
switch(env.JOB_NAME)
{
case "pipeline1":
url = ' [email protected]'
branch = 'release'
break
case "pipeline2":
url = '[email protected]'
branch = 'master'
break
case "pipeline3":
url = '[email protected]'
branch = 'develop'
break
default:
echo "############ wrong pipeline name ############"
break
}
checkout([
$class: 'GitSCM',
branches: [[name: "$branch"]], //這裡必須用"$branch"
doGenerateSubmoduleConfigurations: false,
extensions: [
[$class: 'CleanBeforeCheckout'],
[$class: 'RelativeTargetDirectory', relativeTargetDir: 'code'],
[$class: 'SubmoduleOption', disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', timeout: 3, trackingSubmodules: false]],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: 'xxx',
url: "$url"]]]) //這裡必須用"$url"
}
}
}
}
}