Trouble reading Secrets from Jenkins Credential Manager in Multi Branch Pipeline job using Credential Parameter

北城以北 提交于 2019-12-25 02:15:48

问题


I have a Jenkins multi branch pipeline job that uses a secret value in Jenkinsfile:

pipeline {
  agent any
  stages {
    stage('Test') {
      steps {
        echo "DOCKER_REGISTRY_USER is ${env.DOCKER_REGISTRY_USER_NSV}"
      }
    }
  }
}

The secret value is stored in Credentials Manager as secret text with the ID DOCKER_REGISTRY_USER_NSV:

I'm trying to read this value in Jenkinsfile as shown above but I get the following output that prints out the value null for my secret:

[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] echo
DOCKER_REGISTRY_USER is null
[Pipeline] sh

I also tried referencing the secret text in my pipeline like this:

echo "DOCKER_REGISTRY_USER is ${DOCKER_REGISTRY_USER_NSV}"

But then I get this error when running the Jenkins job:

groovy.lang.MissingPropertyException: No such property: DOCKER_REGISTRY_USER_NSV for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:264)

I think I need to bind that credential to the job but I don't see an option to do that for a Multi-Branch Pipeline job, the way you can for a Freestyle or Pipeline job.

How can I use a secret credential in a Multi Branch Pipeline job?


回答1:


You can use credentials() helper method to archive your purpose.

pipeline {
    agent any

    environment {
        DOCKER_REGISTRY_USER = credentials('DOCKER_REGISTRY_USER_NSV') 
                               // put the ID of credential as credentials()'s parameter.
    }

    stages {

        stage('Test') {
            steps {
                echo "DOCKER_REGISTRY_USER is ${DOCKER_REGISTRY_USER}"
            }
        }
   }

}


来源:https://stackoverflow.com/questions/54875645/trouble-reading-secrets-from-jenkins-credential-manager-in-multi-branch-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!