如何在Jenkins脚本化流水线Jenkinsfile中配置RedeployPublisher
在Jenkins脚本化流水线中配置Maven构件部署到仓库
我来帮你把config.xml里的RedeployPublisher配置转换成Jenkins脚本化流水线的代码。先拆解下你原配置对应的核心功能:
<id>snapshots</id>:指定Maven仓库的标识ID<url>http://repo.internal.com/content/repositories/snapshots/</url>:目标Maven仓库的地址<uniqueVersion>true</uniqueVersion>:为快照版本生成带时间戳的唯一构件(这是Maven快照版本的默认行为)<evenIfUnstable>false</evenIfUnstable>:仅当构建成功时才执行部署,不稳定或失败的构建跳过部署
下面是对应的脚本化流水线实现,我会分场景说明:
基础实现(无认证场景)
如果目标仓库不需要认证,直接用以下代码即可:
node { stage('Checkout Code') { checkout scm // 自动拉取流水线配置的源码仓库代码 } stage('Build Project') { // 先执行构建,确保代码能正常编译打包 sh 'mvn clean install' } stage('Deploy to Maven Snapshot Repository') { // 对应evenIfUnstable=false:只有构建成功才执行部署 if (currentBuild.result == null || currentBuild.result == 'SUCCESS') { // 执行Maven deploy命令,指定目标仓库的ID和地址 sh ''' mvn deploy \ -DaltDeploymentRepository=snapshots::default::http://repo.internal.com/content/repositories/snapshots/ \ -DuniqueVersion=true ''' // 注:如果项目版本是快照版本(带-SNAPSHOT后缀),uniqueVersion=true是默认值,可以省略这个参数 } else { echo "构建状态为${currentBuild.result},跳过部署步骤" } } }
带认证的场景(仓库需要用户名密码)
如果你的Maven仓库需要认证,先在Jenkins中创建对应的用户名密码凭证(比如凭证ID设为maven-snapshots-creds),再用withCredentials步骤传递认证信息:
node { stage('Checkout Code') { checkout scm } stage('Build Project') { sh 'mvn clean install' } stage('Deploy to Maven Snapshot Repository') { if (currentBuild.result == null || currentBuild.result == 'SUCCESS') { withCredentials([usernamePassword( credentialsId: 'maven-snapshots-creds', usernameVariable: 'REPO_USER', passwordVariable: 'REPO_PASS' )]) { sh ''' mvn deploy \ -DaltDeploymentRepository=snapshots::default::http://repo.internal.com/content/repositories/snapshots/ \ -Dmaven.deploy.username=${REPO_USER} \ -Dmaven.deploy.password=${REPO_PASS} ''' } } else { echo "构建状态为${currentBuild.result},跳过部署步骤" } } }
关键参数对应说明
-DaltDeploymentRepository:格式为仓库ID::仓库布局::仓库URL,完全对应原配置里的<id>和<url>-DuniqueVersion=true:直接对应<uniqueVersion>true</uniqueVersion>,快照版本可省略- 构建状态判断:通过
currentBuild.result控制仅成功构建才执行部署,完美匹配<evenIfUnstable>false</evenIfUnstable>的逻辑
内容的提问来源于stack exchange,提问作者Janitha Madushan
相关产品推荐
相关产品推荐

