如何在Blue Ocean重跑Jenkins Pipeline时获取上次构建参数?
解决Jenkins Blue Ocean重跑流水线时参数丢失的问题
方法1:从历史构建中回溯获取参数值
通过判断当前构建是否为重跑,然后从上一次(或最近一次有效)构建中提取目标参数值。无需额外插件,直接利用Jenkins流水线API实现。
示例代码:
// 定义函数:从最近一次有效构建中获取指定参数 def getLastValidParam(String paramName) { def build = currentBuild.previousBuild while (build != null) { // 跳过未完成或被终止的构建 if (build.result in ['SUCCESS', 'FAILURE']) { def paramValue = build.buildVariables.get(paramName) if (paramValue != null) { return paramValue } } build = build.previousBuild } return null } // 处理givenGitBranch参数 def givenGitBranchValue = params.givenGitBranch // 如果当前是重跑构建且参数为空,尝试从历史构建获取 if (givenGitBranchValue == null && currentBuild.buildCauses.any { it.shortDescription.contains('replayed') }) { givenGitBranchValue = getLastValidParam('givenGitBranch') } // 最终分支选择逻辑:优先用处理后的参数,其次用MR源分支 def targetBranch = givenGitBranchValue ?: env.gitlabSourceBranch
注意事项:
- 确保Jenkins流水线有访问构建历史的权限,避免权限报错
- 可根据需求调整“有效构建”的判定条件(例如仅读取成功构建的参数)
方法2:首次运行时持久化参数到构建元数据
在流水线首次运行时,将参数值写入构建的描述信息,重跑时直接从描述中提取参数值。
示例代码:
def givenGitBranchValue = params.givenGitBranch // 首次运行时保存参数到构建描述 if (!currentBuild.buildCauses.any { it.shortDescription.contains('replayed') }) { if (givenGitBranchValue != null) { currentBuild.description = "PersistedParam: givenGitBranch=${givenGitBranchValue}" } } // 重跑时从描述中提取参数 if (givenGitBranchValue == null && currentBuild.description != null) { def paramMatcher = (currentBuild.description =~ /givenGitBranch=(\S+)/) if (paramMatcher.find()) { givenGitBranchValue = paramMatcher.group(1) } } // 分支选择逻辑 def targetBranch = givenGitBranchValue ?: env.gitlabSourceBranch
优势:
- 无需遍历历史构建,直接读取当前构建元数据,性能更优
- 参数值与当前构建绑定,不受其他构建操作的影响
内容的提问来源于stack exchange,提问作者Omer Lerner
相关产品推荐
相关产品推荐

