Reference global credentials in Bash script in Jenkins job

Using the Credentials Binding Plugin, global credentials may be injected into the build context. This is done by checking the checkbox labeled Use secret text(s) or file(s) in the Build Environment section of the job's configuration page. Add a Username and password (separated) binding, choose the specific credential you created, and define your username and password variables.

Here's an example of the Credentials Binding Plugin in use, but with a colon-delimited username/password variable instead of the two separate variables:

Credentials Binding Plugin example

You can then use the username and/or password variables you defined in your shell script. Assuming a username value of foo and a password value of bar...

Username and password binding, variable name USER_CREDENTIALS:

echo $USER_CREDENTIALS # -> foo:bar

Username and password (separated) binding, variable names USER_ID and USER_PASSWORD:

echo $USER_ID          # -> foo
echo $USER_PASSWORD    # -> bar

If your credentials ID is "USER_PASSWORD", you have to read it using eg. the following command: USER_CREDENTIALS = credentials('USER_PASSWORD'). After doing this, the username and password are available in the following environment variables: USER_CREDENTIALS_USR and USER_CREDENTIALS_PSW. Jenkins always adds _USR and _PSW endings to the names of the variables.

Example pipeline (I did not fully tested it, but should work):

pipeline {
    agent any

    environment {
        USER_CREDENTIALS = credentials('USER_PASSWORD')
    }

    stages {
        stage('Run') {
            steps {
                sh "echo $USER_CREDENTIALS_USR"
                sh "echo $USER_CREDENTIALS_PSW"
            }
        }
    }
}

If you get **** (four asterisks) as output, it's ok - Jenkins automatically masks usernames and passwords in the console output.

More information: https://jenkins.io/doc/book/pipeline/jenkinsfile/#usernames-and-passwords .


I couldn't find a straight forward answer for how to use the parameterized Credentials Parameter username and password as environmental variables in a bash script. The following worked for me:

  1. Add a Credentials Parameter. I called it "CREDENTIALS". Credential type "Username and password." Credentials Parameter Screenshot

  2. In the Build Environment check "Use secret text(s) or files(s)".

  3. Add a "Username and password (separated)" binding. I set my Username Variable to USER and Password Variable to PW. For Credentials select "Parameter expression" and put in the name from step one. In this case it would be ${CREDENTIALS}. Credentials Binding Screenshot

  4. Now ${USER} and ${PW} are available to the bash script.