如何在Jenkins声明式流水线中更新构建参数,解决build属性不存在报错
错误原因
你遇到的groovy.lang.MissingPropertyException: No such property: build for class: WorkflowScript报错,是因为Jenkins声明式流水线默认不会注入build变量,流水线内置的全局变量是currentBuild,你需要通过它获取当前构建的实例对象才能调用对应的参数操作接口。
修正后的可用方案
方案1:脚本块中调用内部API修改构建参数
这是可以直接实现你需求的方案,修正后的代码如下:
pipeline { agent any stages { stage('更新构建参数') { steps { script { // 通过currentBuild获取当前构建实例 def build = currentBuild.rawBuild def reporter = build.buildVariableResolver.resolve("reporter") if (reporter != null) { reporter = reporter.tokenize(',').find {item -> item.contains('displayName')}.tokenize('=')[1] } else { reporter = "" } // 构建新的参数值,直接传入变量不要加多余的引号包裹 def reporterParameter = new StringParameterValue("reporter", reporter) build.addOrReplaceAction(new ParametersAction(reporterParameter)) // 可选:同步更新环境变量,让后续步骤不需要调用API就能直接拿到修改后的值 env.reporter = reporter } } } // 后续阶段可以直接用 $reporter 读取修改后的值 stage('验证参数') { steps { echo "修改后的reporter值为:${env.reporter}" } } } }
注意事项
- 上述代码用到了Jenkins内部非公开API,首次运行时会触发权限拦截,需要管理员进入「Manage Jenkins」->「In-process Script Approval」页面批准对应的方法调用权限
- 该修改仅对本次构建的参数记录生效,不会更改流水线的全局默认参数配置
方案2:符合声明式最佳实践的替代方案
声明式流水线没有原生提供修改构建参数的语法,如果你只是需要在本次流水线的后续步骤中使用修改后的reporter值,不需要修改构建的历史参数记录,完全可以直接通过环境变量传递,不需要调用内部API,也不需要申请额外权限:
pipeline { agent any parameters { string(name: 'reporter', defaultValue: '', description: '原始上报人参数') } environment { // 直接在环境变量块处理参数值,也可以放在script块里赋值 REPORTER = """${ params.reporter ? params.reporter.tokenize(',').find {it.contains('displayName')}.tokenize('=')[1] : '' }""" } stages { stage('验证参数') { steps { echo "处理后的reporter值为:${env.REPORTER}" } } } }
内容的提问来源于stack exchange,提问作者Kucharsky
相关产品推荐
相关产品推荐

