如何在不使用withCredentials.usernamePassword屏蔽PASSWORD的情况下重用Jenkins凭据?

问题描述 投票:1回答:1

Background

  • 我正在使用脚本管道和共享库。

我们所有的实现都在src目录下,我在管道中重用了引用:

def static myFunction(steps, context) {
  steps.withCredentials([steps.usernamePassword(
      credentialsId: 'credentialsId',
      usernameVariable: 'GITHUB_USERNAME',
      passwordVariable: 'GITHUB_PASSWORD')]) {

     // use of steps.env.GITHUB_PASSWORD
  }
}
  • 我需要使用相同的凭据对Github Enterprise进行2次API调用,该凭据被设置为UsernamePassword凭证尽管第一次调用按预期工作,但第二次调用因env.GITHUB_PASSWORD值被屏蔽而失败详细信息

https://wiki.jenkins.io/display/JENKINS/Credentials+Binding+Plugin中所述,问题可能与多次使用时屏蔽凭据绑定的方式有关。也就是说,一旦我们使用$ {env.PASSWORD}一次,它将掩盖相同值的所有使用。

Detail

我正在使用curl,我需要生成URL

def teamMembersApi = sh(curl -H 'Authorization: token ${env.PASSWORD}' ${githubRepoApi}")

此调用的响应是另一个API URL,我使用“teamMembersApi”创建了另一个URL。所以,拨打第二个电话......

def teamMembers = sh("curl -H 'Authorization: token ${env.PASSWORD}' ${teamMembersApi}")

此时,$ {env.PASSWORD}的值被屏蔽,因此第二次调用因证书无效而失败

Questions

据我所知,这是通过任何方法访问值的“屏蔽”的结果,这将导致“toString()”使其无法在字符串中重用...

  • 如何重新使用相同的凭据,即使它们有资格被屏蔽也是如此?

Verifications

  • 我尝试使用2个步骤.withCredentials
  • 我尝试使用httpRequest步骤不引用变量

使用httpRequest,我得到了一个格式正确的URL的MalformedURLException ...我确保URL是String格式并且有协议......

java.net.MalformedURLException: no protocol: https://github.company.com/org/repo
jenkins jenkins-pipeline credentials
1个回答
1
投票

您可以随时使用username/password区域内的withCredentials。但请记住,username/password只能在withCredentials区内生存。

我在下面的代码中使用了相同的username/password两次,效果很好。

node('docker') {
  withCredentials([steps.usernamePassword(
      credentialsId: 'ba2e4f46-56f1-4467-ae97-17b356d7f854',
      usernameVariable: 'JENKINS_USERNAME',
      passwordVariable: 'JENKINS_PASSWORD')]) {

     def log = sh(
         returnStdout: true,
         script: "curl -u ${env.JENKINS_USERNAME}:${env.JENKINS_PASSWORD} -k ${env.BUILD_URL}" + 'consoleText').trim()

     def pipelineSteps = sh(
         returnStdout: true,
         script: "curl -u ${env.JENKINS_USERNAME}:${env.JENKINS_PASSWORD} -k ${env.BUILD_URL}" + 'flowGraphTable').trim()

     echo '\n## build log ##\n' + log

     echo '\n## pipelineSteps ##\n' + pipelineSteps
  }

  echo "JENKINS_USERNAME: ${env.JENKINS_USERNAME}" 
  // print JENKINS_USERNAME: null 
  // because JENKINS_USERNAME's lifecycle is limited inside withCredentials blok.      
}

代码中的另一个问题,如果你没有为步骤returnStdout: true指定选项sh,它应该返回null。例如:def output = sh('command')output将是null

© www.soinside.com 2019 - 2024. All rights reserved.