问题描述
如何仅在构建特定分支时运行构建步骤/阶段?
How do you run a build step/stage only if building a specific branch?
例如,仅当分支名为 deployment
时才运行部署步骤,其他一切保持不变.
For example, run a deployment step only if the branch is called deployment
, leaving everything else the same.
推荐答案
在声明式管道语法中做同样的事情,下面是几个例子:
Doing the same in declarative pipeline syntax, below are few examples:
stage('master-branch-stuff') {
when {
branch 'master'
}
steps {
echo 'run this stage - ony if the branch = master branch'
}
}
stage('feature-branch-stuff') {
when {
branch 'feature/*'
}
steps {
echo 'run this stage - only if the branch name started with feature/'
}
}
stage('expression-branch') {
when {
expression {
return env.BRANCH_NAME != 'master';
}
}
steps {
echo 'run this stage - when branch is not equal to master'
}
}
stage('env-specific-stuff') {
when {
environment name: 'NAME', value: 'this'
}
steps {
echo 'run this stage - only if the env name and value matches'
}
}
出现更有效的方法-https://issues.jenkins-ci.org/browse/JENKINS-41187
还看-https://jenkins.io/doc/book/pipeline/syntax/#when
指令 beforeAgent true
可以设置为避免启动代理来运行条件,如果条件不需要 git state 来决定是否运行:
when { beforeAgent true; expression { return isStageConfigured(config) } }
更新
新的 WHEN 子句
参考:https://jenkins.io/blog/2018/04/09/whats-in-declarative
equals - 比较两个值 - 字符串、变量、数字、布尔值 -如果它们相等,则返回 true.老实说,我不确定我们是如何错过的早点添加这个!你可以做不等于"使用 not 的比较{ 也等于 ... } 组合.
changeRequest - 以最简单的形式,如果这将返回 truePipeline 正在构建变更请求,例如 GitHub 拉取请求.您还可以对变更请求进行更详细的检查,允许您询问这是针对主人的更改请求吗?分行?"以及更多.
changeRequest - In its simplest form, this will return true if thisPipeline is building a change request, such as a GitHub pull request.You can also do more detailed checks against the change request,allowing you to ask "is this a change request against the masterbranch?" and much more.
buildingTag - 一个简单的条件,只检查管道是否是针对 SCM 中的标签运行,而不是针对分支或特定提交参考.
buildingTag - A simple condition that just checks if the Pipeline isrunning against a tag in SCM, rather than a branch or a specificcommit reference.
tag - 更详细的 buildingTag 等价物,可让您检查针对标签名称本身.
tag - A more detailed equivalent of buildingTag, allowing you to checkagainst the tag name itself.
这篇关于Jenkins 管道中的条件步骤/阶段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!