Search code examples
jenkinsjenkins-pipelinepassword-encryption

Jenkins declarative pipeline mask parameter password in console logs


I would like to mask the password provided as a parameter in Jenkins job and it's using the declarative pipeline syntax. I don't want to save any credentials and use them. As this will be the credentials entered by the user running the job specific to them.

I have already tried MaskPasswordsBuildWrapper, but it doesn't work. I would appreciate if someone can provide working example.

This is my Jenkinsfile for declarative pipeline using MaskPasswordsBuildWrapper which doesn't work:

pipeline {

    agent none

    options {
        skipDefaultCheckout()
        skipStagesAfterUnstable()
    }

    parameters {
        string(name: 'userid', defaultValue: 'master', description: 'Enter User ID')
        password(name: 'passwd', defaultValue: 'secret', description: 'Enter Password')
    }

    stages {
        stage('Test') {
            agent {
                label 'someLabel'
            }
            steps {
                script {
                    wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[var: 'PSWD', password: params.passwd]], varMaskRegexes: []]) {
                        sh "echo PSWD: ${PSWD}"
                    }
                }
            }
        }
    }
}

Solution

  • I was able to mask the password in console logs, below is the working code:

    pipeline {
    
        agent none
    
        options {
            skipDefaultCheckout()
            skipStagesAfterUnstable()
        }
    
        parameters {
            string(name: 'userid', defaultValue: 'master', description: 'Enter User ID')
            password(name: 'passwd', defaultValue: 'secret', description: 'Enter Password')
        }
    
        stages {
            stage('Test') {
                agent {
                    label 'someLabel'
                }
                steps {
                    script {
                        wrap([$class: 'MaskPasswordsBuildWrapper', varPasswordPairs: [[password: "${passwd}", var: 'PSWD']]]) {
                            sh '''echo PSWD: ${passwd}'''
                        }
                    }
                }
            }
        }
    }