Jenkins自由风格项目:如何从Shell脚本读取凭证参数为用户名:密码
解决方案
方法1:使用自动生成的环境变量(最简方案)
在自由风格项目中添加用户名和密码类型的凭证参数(名称为nexus_credentials)后,Jenkins会自动生成两个环境变量:
nexus_credentials_USR:凭证用户名nexus_credentials_PSW:凭证密码
在「执行shell」步骤中,直接拼接这两个变量用于curl的-u选项即可:
curl -u "${nexus_credentials_USR}:${nexus_credentials_PSW}" https://your-nexus-repo-url/repository/your-target-repo/your-file-name -T ./local-file-path
用双引号包裹变量,避免用户名/密码含特殊字符时触发命令格式错误。
方法2:Groovy脚本中获取凭证(脚本场景)
自由风格项目不支持Pipeline的withCredentials DSL,直接调用会抛出MissingMethodException。需通过Jenkins凭证API获取:
import com.cloudbees.plugins.credentials.CredentialsProvider import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials // 获取当前构建实例 def build = Thread.currentThread().executable // 根据参数名称获取凭证对象 def credentials = CredentialsProvider.findCredentialById( build.buildVariableResolver.resolve("nexus_credentials"), StandardUsernamePasswordCredentials.class, build ) // 提取用户名和明文密码 def username = credentials.username def password = credentials.password.plainText // 执行curl命令示例 def uploadCmd = "curl -u '${username}:${password}' https://your-nexus-repo-url/repository/your-target-repo/your-file-name -T ./local-file-path" def process = uploadCmd.execute() process.waitFor() // 输出命令执行结果 println "命令输出:${process.in.text}" println "错误信息:${process.err.text}"
注意事项
- 确保Jenkins执行用户拥有凭证访问权限
- 仅适用于「用户名和密码」类型的凭证,其他类型(如SSH密钥)需调整对应凭证类
内容的提问来源于stack exchange,提问作者aiman
相关产品推荐
相关产品推荐

