如何将PowerShell脚本输出传入Jenkins参数实现vSphere模板下拉选择
问题根因
- 第一:当前
findtemplates函数仅返回了PowerShell命令的字符串文本,没有实际调用Jenkins的执行方法运行命令获取返回值 - 第二:声明式Pipeline的
parameters块是在Jenkins任务初始化阶段解析的,该阶段不允许执行外部命令、调用第三方接口这类操作 - 第三:
choice参数的choices字段需要接收字符串数组格式的可选值,PowerShell返回的原始输出需要做格式清洗
可行解决方案
方案1:使用Active Choices插件(最常用方案)
先安装Jenkins的「Active Choices Plugin」,然后直接在参数配置里写Groovy脚本执行命令,示例代码如下:
// Active Choices参数的Groovy脚本内容 def cmd = "powershell -Command \"Connect-VIServer -server <你的vCenter地址> -User <账号> -Password <密码> -Force | Out-Null; (Get-Template).Name\"" def proc = cmd.execute() proc.waitFor() // 清洗输出,按行分割过滤空值后返回 return proc.in.text.split("\n").trim().findAll { it }
配置参数类型选择「Active Choices Parameter」,名称设为Template,把上面的脚本贴到Script框里即可。
方案2:用脚本式Pipeline动态生成参数
如果不想装额外插件,可以用脚本式Pipeline在node块里先执行命令获取模板列表,再用input步骤动态生成选择参数:
node { stage('获取模板列表') { // 实际执行PowerShell命令获取输出 def templateOutput = powershell returnStdout: true, script: ''' Connect-VIServer -server <你的vCenter地址> -User <账号> -Password <密码> -Force | Out-Null Get-Template | Select-Object -ExpandProperty Name ''' // 清洗输出为数组 def templateList = templateOutput.split("\n").trim().findAll { it } // 动态生成选择参数 def userInput = input message: '选择部署模板', parameters: [ choice(name: 'Template', choices: templateList, description: '选择要使用的vSphere模板') ] // 后续步骤直接使用userInput.Template即可 } // 其他部署阶段 }
注意事项
- 执行PowerShell的Jenkins节点必须提前安装VMware PowerCLI模块,可提前执行
Install-Module -Name VMware.PowerCLI -Scope AllUsers -Force安装 - vCenter账号密码不要硬编码在代码里,建议存在Jenkins凭据中,调用时用
credentials()方法获取 - 如果执行PowerShell时报证书验证错误,可以在Connect-VIServer前加
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false处理
内容的提问来源于stack exchange,提问作者Sosh
相关产品推荐
相关产品推荐

