如何在Jenkins声明式管道中获取DynamicReferenceParameter输入值?
问题分析
你遇到的params.choice2返回null的原因有两个:
omitValueField: true会隐藏参数的默认值输入框,导致Jenkins无法捕获用户输入的内容- 返回的HTML input标签
name属性是Aws而非参数名choice2,Jenkins无法将输入值绑定到params.choice2
解决方案
修改DynamicReferenceParameter的配置和对应脚本,具体调整如下:
修改点1:移除omitValueField配置
删除omitValueField: true(默认值为false),确保Jenkins能处理参数的提交值。
修改点2:调整HTML input的name属性
将返回的input标签的name设置为参数名choice2,让用户输入的值能被Jenkins捕获并赋值给params.choice2。
修改点3:处理choice1为bbb的情况
当choice1是bbb时,返回隐藏input标签并设置默认值,确保参数不会返回null。
修改后的完整代码
properties([ parameters([ [ $class: 'ChoiceParameter', choiceType: 'PT_RADIO', description: 'Select a choice', filterLength: 1, filterable: false, name: 'choice1', randomName: 'choice-parameter-7601235200970', script: [ $class: 'GroovyScript', fallbackScript: [ classpath: [], sandbox: false, script: 'return ["ERROR"]' ], script: [ classpath: [], sandbox: true, script: 'return[\'aaa\',\'bbb\']' ] ] ], [ $class: 'DynamicReferenceParameter', choiceType: 'ET_FORMATTED_HTML', name: 'choice2', referencedParameters: 'choice1', description: 'Active Choices Reactive parameter', randomName: 'choice-parameter-7601237141171', script: [ $class: 'GroovyScript', fallbackScript: [ classpath: [], sandbox: false, script: 'return ["error"]' ], script: [ classpath: [], sandbox: true, script: ''' if(choice1.equals("aaa")){ return "<input name='choice2' value='' class='setting-input' type='text' placeholder='请输入内容'>" } else { return "<input type='hidden' name='choice2' value='Not Required'>Not Required" } ''' ] ] ] ]) ]) pipeline { agent any stages { stage('Print the Values') { steps { script{ echo "choice1: ${params.choice1}" echo "choice2: ${params.choice2}" } } } } }
说明
- 选择choice1为
aaa时,页面显示输入框,用户输入的内容会被赋值给params.choice2 - 选择choice1为
bbb时,页面显示"Not Required",同时通过隐藏input将choice2的值设为"Not Required",避免返回null - 移除
omitValueField: true后,Jenkins能够正确捕获参数的提交值
内容的提问来源于stack exchange,提问作者Mohammed Suhail
相关产品推荐
相关产品推荐

