如何在 dsl 中使用 jenkins 插件获取用户名和密码?

use*_*691 2 jenkins jenkins-plugins jenkins-job-dsl jenkins-groovy

我是 jenkins 新手,我正在尝试使用凭证插件在 dsl 中使用凭证

模板.xml

<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
      <scope>GLOBAL</scope>
      <id>PROD</id>
      <description>prod credentials</description>
      <username>prod</username>
      <password>{{ encrypted_password_prod }}</password
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
Run Code Online (Sandbox Code Playgroud)

我已在 jenkins 中将凭据定义为 username with password 。上述加密值保存在ansible中。

我的问题是我应该如何在我的 dsl 中调用它们

Map credentials = [:]

credentialsBinding {
                    credentials.each { key, value ->
                        string("${key}", "${value}")
                    }


.credentials(["TF_VAR_username": "PROD" ,"TF_VAR_password" : "password_prod"])
Run Code Online (Sandbox Code Playgroud)

错误:

22:11:16 致命:凭证“PROD”的类型为“带密码的用户名”,其中预期为“org.jenkinsci.plugins.plaincredentials.StringCredentials”

小智 5

您可以将凭据放入 Jenkins 密钥库中(Jenkins -> 凭据 -> 系统 -> 全局凭据 -> 添加凭据),然后使用 withCredentials 块在管道中引用它们,如下所示:

node {
  withCredentials([usernameColonPassword(credentialsId: 'mylogin', variable: 'USERPASS')]) {
    sh '''
      set +x
      curl -u "$USERPASS" https://private.server/ > output
    '''
  }
}
Run Code Online (Sandbox Code Playgroud)

更多信息在这里:https ://jenkins.io/doc/pipeline/steps/credentials-binding/