一.簡介
when指令允許pipeline根據給定的條件,決定是否執行階段內的步驟。when指令必須至少包含一個條件。when指令除了支持branch判斷條件,還支持多種判斷條件。
如下使用
stage('Example Deploy') {
when {
branch 'production'
}
steps {
echo 'Deploying'
}
}
二.選項
單獨判斷
changelog :如果版本控制庫的changelog符合正則表達式,則執行
when {
changelog '.*^\\[DEPENDENCY\\] .+$'
}
changeset :如果版本控制庫的變更集合中包含一個或多個文件符合給定的Ant風格路徑表達式,則執行
when {
changeset "**/*.js"
}
environment :如果環境變量的值與給定的值相同,則執行
when {
environment name: 'DEPLOY_TO', value: 'production'
}
equals :如果期望值與給定的值相同,則執行
when {
equals expected: 2, actual: currentBuild.number
}
expression :如果Groovy表達式返回的是true,則執行。當表達式返回的是字符串時,它必須轉換成布爾類型或null ;否則,所有的字符串都被當作true處理。
when {
expression {
return env.BRANCH_NAME != 'master';
}
}
buildingTag :如果pipeline所執行的代碼被打了tag,則執行
when {
buildingTag()
}
tag:如果pipeline所執行的代碼被打了tag,且tag名稱符合規則,則執行。如果tag的參數為空,即tag ( ),則表示不論tag名稱是什么都執行,與buildingTag的效果相同。
when {
tag "release-*"
}
tag條件支持comparator參數,支持的值如下。
EQUALS:簡單的文本比較
when {
tag pattern "release-3.1", comparator: "EQUALS"
}
GLOB(默認值) :Ant風格路徑表達式。由於是默認值,所以使用時一般省略。
when {
tag pattern "release-*", comparator: "GLOB"
}
REGEXP∶正則表達式
when {
tag pattern "release-\\d+", comparator: "REGEXP"
}
條件組合
以上介紹的都是單條件判斷,when指令還可以進行多條件組合判斷。
allOf :所有條件都必須符合。下例表示當分支為master且環境變量DEPLOY_TO的值為production時,才符合條件。注意,多條件之間使用分號分隔。
when {
anyof {
branch 'master';
environment name: 'DEPLOY_TO', value: 'production'
}
}
anyOf:其中一個條件為true,就符合。下例表示master分支或staging分支都符合條件。
when {
anyof {
branch 'master';
branch 'staging'
}
}
