Jenkins Publish Over SSH流水线多服务器部署参数化配置问询
解决方案
方案1:使用Active Choices插件实现动态下拉参数(推荐,支持多选)
- 第一步:安装
Active Choices Plugin插件,重启Jenkins生效。 - 第二步:进入目标Job配置页,在参数化构建过程模块添加「Active Choices Parameter」:
- 参数名设置为
DEPLOY_SERVER,描述自定义为“选择部署目标SSH服务器” - 脚本类型选择「Groovy Script」,填入以下获取SSH服务器列表的代码:
import jenkins.model.Jenkins import jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin // 获取Publish Over SSH插件的全局配置 def sshPlugin = Jenkins.instance.getExtensionList(BapSshPublisherPlugin.class)[0] // 提取所有已配置的SSH服务器名称 def allServerNames = sshPlugin.getHostConfigurations()*.name // 可按需添加过滤逻辑,比如只返回前缀为server-instance的服务器 // allServerNames = allServerNames.findAll { it.startsWith('server-instance') } return allServerNames- 如需支持同时部署到多台服务器,可选择「Active Choices Reactive Parameter」,并勾选「Allow multiple selections」选项。
- 若脚本执行提示权限错误,进入「Manage Jenkins >> In-process Script Approval」页面批准对应脚本即可。
- 参数名设置为
- 第三步:修改流水线的部署阶段配置,将硬编码的服务器名称替换为参数:
单台部署的代码示例:
多选多台部署的代码示例:stage('Deploy to Server'){ def pom = readMavenPom file: 'pom.xml' script { sshPublisher(publishers: [sshPublisherDesc(configName: DEPLOY_SERVER, transfers: [sshTransfer(cleanRemote:true, sourceFiles: "target/${env.PROJECT_NAME}-${pom.version}.jar", removePrefix: "target", remoteDirectory: "${env.PROJECT_NAME}", execCommand: "mv ${env.PROJECT_NAME}/${env.PROJECT_NAME}-${pom.version}.jar ${env.PROJECT_NAME}/${env.PROJECT_NAME}.jar"), sshTransfer( execCommand: "/etc/init.d/${env.PROJECT_NAME} restart -Dspring.profiles.active=${PROFILE}" ) ]) ]) } }stage('Deploy to Server'){ def pom = readMavenPom file: 'pom.xml' script { // 兼容单选/多选参数格式 def deployServerList = DEPLOY_SERVER instanceof String ? [DEPLOY_SERVER] : DEPLOY_SERVER // 为每个选中的服务器生成发布配置 def publisherList = deployServerList.collect { serverName -> sshPublisherDesc(configName: serverName, transfers: [sshTransfer(cleanRemote:true, sourceFiles: "target/${env.PROJECT_NAME}-${pom.version}.jar", removePrefix: "target", remoteDirectory: "${env.PROJECT_NAME}", execCommand: "mv ${env.PROJECT_NAME}/${env.PROJECT_NAME}-${pom.version}.jar ${env.PROJECT_NAME}/${env.PROJECT_NAME}.jar"), sshTransfer( execCommand: "/etc/init.d/${env.PROJECT_NAME} restart -Dspring.profiles.active=${PROFILE}" ) ]) } sshPublisher(publishers: publisherList) } }
方案2:无额外插件,直接在流水线中定义动态参数
如果不想安装新插件,可以直接在流水线开头通过properties定义动态选项的参数,代码如下:
node { // 流水线最开头添加动态参数配置 properties([ parameters([ choice( name: 'DEPLOY_SERVER', // 直接调用API获取已配置的SSH服务器列表作为下拉选项 choices: jenkins.model.Jenkins.instance.getExtensionList(jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin.class)[0].getHostConfigurations()*.name, description: '选择部署目标SSH服务器' ) ]) ]) // 后面的Checkout、Build、Deploy阶段和之前一致,Deploy阶段用${DEPLOY_SERVER}替换硬编码的服务器名即可 stage('Checkout') { git([url: '.............', branch: 'myBranch', credentialsId: 'mycredentials']) } // 其余阶段省略... }
注意:该方案同样需要先在「Manage Jenkins >> In-process Script Approval」中批准API调用权限,否则会执行失败。
内容的提问来源于stack exchange,提问作者pvpkiran
相关产品推荐
相关产品推荐

