You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins声明式流水线中向Gradle传递Nexus凭据解决401错误

解决Jenkins流水线中Gradle上传Nexus报401权限错误的问题

我来帮你搞定这个401权限问题!核心原因很明确:你在Jenkins里通过withCredentials注入的是shell环境变量,但Gradle里却用System.properties去读取——这俩根本不是一个东西,所以Gradle拿不到用户名密码,自然被Nexus拒绝了。下面给你两种直接可行的解决方案:

方法1:把Jenkins环境变量作为Gradle系统属性传递

修改Jenkins流水线里的sh命令,把环境变量通过-D参数传给Gradle(这是匹配你现有Gradle配置的最快方式):

withCredentials([usernamePassword(credentialsId: 'asdf23432-fe69-1234-2222-ffa65yteec2c', passwordVariable: 'NEXUS_PASSWORD', usernameVariable: 'NEXUS_USER')]) { 
    sh "./gradlew upload -DNEXUS_USER=$NEXUS_USER -DNEXUS_PASSWORD=$NEXUS_PASSWORD --debug" 
}

这样你的Gradle现有配置里的System.properties['NEXUS_USER']就能正确拿到值了。

方法2:Gradle直接读取shell环境变量

如果不想修改Jenkins的命令,也可以改Gradle的配置,用System.getenv()直接读取shell环境变量:

ext{ 
    nexusUser = System.getenv('NEXUS_USER') 
    nexusPassword = System.getenv('NEXUS_PASSWORD') 
} 

uploadArchives { 
    repositories { 
        mavenDeployer { 
            snapshotRepository(url: 'http://somerepo'){ 
                authentication(userName: nexusUser, password: nexusPassword) 
            } 
        } 
    } 
}

这种方式更直接,因为withCredentials注入的变量会成为当前shell的环境变量,Gradle运行在同一个shell进程里,所以能直接通过System.getenv获取。

额外验证步骤

为了确保万无一失,你可以加两步验证:

  • 在Jenkins的sh命令里加一行echo $NEXUS_USER,确认环境变量已经正确注入
  • 检查Nexus的SNAPSHOT仓库是否给该用户分配了上传权限,以及仓库URL是否拼写正确

内容的提问来源于stack exchange,提问作者codependent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:17:44