How to mask a password field in Jenkins Pipeline project?

半腔热情 提交于 2019-12-08 20:38:13

问题


When a password property is defined in a Jenkinsfile:

properties([
    parameters([
        password(name: 'KEY', description: 'Encryption key')
    ])
])

Jenkins prompts users to provide its value every time the pipeline is executed:

I want this parameter to be masked so that echo ${KEY} does not print the actual value passed by the user. However, at the moment echoing it prints the provided value verbatim:

properties([
    parameters([
        password(name: 'KEY', description: 'Encryption key')
    ])
])

node {
    stage('Stage 1') {
        # Will print the actual value of the KEY, verbatim
        sh "echo ${KEY}"
    }
}

Also it seems that the Mask Passwords plugin does not work with Jenkins pipelines, so using that is not an option.

Is there a way to mask these password-typed parameters in the build logs?


回答1:


You'll want to use the mask passwords plugin. Here's a Jenkinsfile example taken from my shared pipeline library.

properties([
    parameters([
        password(name: 'KEY', description: 'Encryption key')
    ])  
])  

node {
    stage('Stage 1') {
       // Will print the masked value of the KEY, replaced with ****
       wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[var: 'KEY', password: KEY]], varMaskRegexes: []]) {
            sh "echo ${KEY}"
        }   
    }   
}

Other than existing suggestions on withCredentials, there's not much to add. However, of you're automatically generating your jobs via templates and you're setting a default password, then you might want to make use of hudson.util.Secret to secure your templates.




回答2:


You can use Jenkins Credentials plugin.With this plugin you can create a credential with an ID for use in your pipeline:

The code will be:

withCredentials([string(credentialsId: 'pass', variable: 'password1')]) {
     echo "My password is '${password1}'!"
}

In your user case:

node {
    stage('Echo') {
        withCredentials([string(credentialsId: 'pass', variable: 'password1')]) {
            echo "'${password1}'!"
        }
    }
}

Note: The password will be masked only in the withCredentials block.



来源:https://stackoverflow.com/questions/46659862/how-to-mask-a-password-field-in-jenkins-pipeline-project

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