jenkins教程:jenkinsfile语法之when
when
when
指令位于stage指令中,允许流水线根据给定的条件决定是否应该执行阶段,必须包含至少一个条件。
支持以下嵌套条件:
- branch:当正在构建的分支与分支模式匹配时执行这个阶段, 例如:
when { branch 'master' }
。注意,只适用于多分支流水线。 -
buildingTag
:当构建正在构建标记时执行该阶段。例如:when {buildingTag()}
- environment:当指定的环境变量是给定的值时,执行这个步骤, 例如:
when { environment name: 'DEPLOY_TO', value: 'production' }
-
changelog
:如果构建的SCM变更日志包含一个给定的正则表达式模式,则执行该阶段,例如:when { changelog '.*^\\[DEPENDENCY\\] .+$' }
-
changeset
:如果构建的SCM变更集包含一个或多个匹配给定模式的文件,则执行该阶段。例如:when { changeset "**/*.js" }
-
changeRequest
:如果当前构建是为了一个“change request”(比如GitHub的Pull request, GitLab上的Merge request, Gerrit中的change等)时执行这个阶段。如果没有传递参数,stage在每次变更请求上运行,例如:when { changeRequest() }
-
environment
:当指定的环境变量设置为给定的值时执行,例如:when { environment name: 'DEPLOY_TO', value: 'production' }
-
equals
:当期望值与实际值相等时执行,例如:when { equals expected: 2, actual: currentBuild.number }
-
expression
:当指定的Groovy表达式为true时执行, 例如:when { expression { return params.DEBUG_BUILD } }
。注意,当表达式返回字符串时,它们必须转换为布尔值,或者返回null来计算为false。简单地返回“0”或“false”仍然会被计算为“true”。 -
tag
:如果TAG_NAME
变量与给定的模式匹配则执行该阶段。例如:when { tag "release-*" }
。如果提供了一个空模式,那么如果存在TAG_NAME变量,则该阶段将执行(与buildingTag()
相同)。 -
not
:当嵌套条件是false
时执行这个阶段,它必须包含一个条件,例如:when { not { branch 'master' } }
-
allOf
:当所有的嵌套条件都为true
时执行,必须包含至少一个条件,例如:when { allOf { branch 'master'; environment name: 'DEPLOY_TO', value: 'production' } }
-
anyOf
:当至少有一个嵌套条件为true
时执行,必须包含至少一个条件,例如:when { anyOf { branch 'master'; branch 'staging' } }
triggeredBy
:当当前构建被给定的参数触发时执行。例如:
when { triggeredBy 'SCMTrigger' }
when { triggeredBy 'TimerTrigger' }
when { triggeredBy 'BuildUpstreamCause' }
when { triggeredBy cause: "UserIdCause", detail: "vlinde" }
在进入 stage
的 agent
前评估 when
- 默认情况下,如果定义了该
stage
的agent
,则stage
的when
条件将在进入该stage
的agent
之后计算。但是,这可以通过在when
块中指定beforeAgent
选项来更改。如果beforeAgent
设置为true
,则首先计算when
条件,只有当条件计算为true
时才进入agent
。
在 input
指令之前评估 when
- 默认情况下,如果定义了
stage
的when
条件,则不会在input
之前求值。但是,这可以通过在when
块中指定beforeInput
选项来更改。如果beforeInput
设置为true
,when
条件将首先计算,只有当条件计算为true时才会进入input
。 -
beforeInput true
优先级高于beforeAgent true
。
在 options
指令之前评估 when
- 默认情况下,如果
stage
定义了任何options
,stage
的when
条件将在进入该stage
的options
之后计算。但是,这可以通过在when
块中指定beforeOptions
选项来更改。如果beforeOptions
设置为true,则首先计算when
条件,只有当条件计算为true
时才会进入options
。 -
beforeOptions true
优先级高于beforeInput true
和beforeAgent true
。
示例脚本:
pipeline {
agent any
stages {
stage('Example Build') {
steps {
echo 'Hello World'
}
}
stage('Deploy1') {
when {
branch 'production1'
}
steps {
echo 'Deploying1'
}
}
stage('Deploy2') {
when {
allOf {
branch 'production2'
environment name: 'DEPLOY_TO', value: 'production2'
}
}
steps {
echo 'Deploying2'
}
}
stage('Deploy3') {
when {
beforeInput true
branch 'production3'
}
input {
message "Deploy to production3?"
id "simple-input"
}
steps {
echo 'Deploying3'
}
}
}
}
links:
https://devtest-notes.readthedocs.io/zh/latest/CI/continuous-integration-for-jenkins-pipeline.html