Search code examples
jenkinsjenkins-pipeline

Hiding password in Jenkins pipeline script


I'm trying to mask a password in my Jenkins build.

I have been trying the mask-passwords plugin.

However, this doesn't seem to work with my Jenkins pipeline script, because if I define the password PASSWD1 and then I use it in the script like this ${PASSWD1}, I am getting:

No such DSL method '$' found among steps [addToClasspath, ansiColor, ansiblePlaybook, ....]

If I use env.PASSWD1, then its value will be resolved to null.

So how should I mask a password in a Jenkins pipeline script?


Solution

  • The simplest way would be to use the Credentials Plugin.

    There you can define different types of credential, whether it's a single password ("secret text"), or a file, or a username/password combination. Plus other plugins can contribute other types of credentials.

    When you create a credential (via the Credentials link on the main Jenkins page), make sure you set an "ID". In the example below, I've called it my-pass. If you don't set it, it will still work, Jenkins will allocate an opaque UUID for you instead.

    In any case, you can easily generate the required syntax with the snippet generator.

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

    This will make the password available in the given variable only within this block. If you attempt to print the password, like I do here, it will be masked.