我该如何访问Jenkins全局配置中定义的密码?
默认情况下不会注入密码,我尝试了下面的代码并成功访问了“全局属性”,但无法访问密码。
def envVars = Jenkins.instance.getGlobalNodeProperties()[0].getEnvVars()
println envVars['MY_VARIABLE']
我该如何访问Jenkins全局配置中定义的密码?
默认情况下不会注入密码,我尝试了下面的代码并成功访问了“全局属性”,但无法访问密码。
def envVars = Jenkins.instance.getGlobalNodeProperties()[0].getEnvVars()
println envVars['MY_VARIABLE']
withCredentials
步骤,该步骤随附于 Credentials Binding Plugin。你是在指Jenkins -> 管理Jenkins -> 全局属性吗?
如果是的话,以下是我们在groovy脚本中检索它们的方法:
import jenkins.model.*
instance = Jenkins.getInstance()
globalNodeProperties = instance.getGlobalNodeProperties()
globalNodeProperties.each {
envVars = it.getEnvVars()
if (envVars.get('ARTIFACTORY_USR') != null) {
artifactory_usr = envVars.get('ARTIFACTORY_USR');
}
if (envVars.get('ARTIFACTORY_PSW') != null) {
artifactory_pwd = envVars.get('ARTIFACTORY_PSW');
}
}
非流水线作业的全局密码注入选项来自EnvInject插件,该插件对于流水线作业并不完全支持: https://plugins.jenkins.io/envinject/
Jenkins Pipeline compatibility
Even though it is possible to set up the EnvInject Job Property and build step in Pipeline, the plugin does not provide full compatibility with Jenkins Pipeline.
Supported use-cases:
Injection of EnvVars defined in the "Properties Content" field of the Job Property
These EnvVars are being injected to the script environment and will be inaccessible via the "env" Pipeline global variable
Please note there is also a known compatibility issue with Durable Task
Plugin 1.13
All other use-cases of the plugin may work incorrectly in Jenkins Pipeline. Please see JENKINS-42614 for more information about unsupported use-cases. There is no short-term plan to fix the compatibility issues though any pull requests to the plugin will be appreciated.
我有同样的使用情况,最终重新创建了全局密码作为凭据。
pipeline {
agent any
stages {
stage("Access the credentials") {
steps {
script {
withCredentials([[
$class:'UsernamePasswordMultiBinding',
credentialsId: 'myCredentialId',
usernameVariable:'username',
passwordVariable:'token'
]]) {
sh '''
curl -u ${username}:${token} -L <replace your git URL> -o master.txt
cat master.txt
'''
}
}
}
}
}
}