Jenkins Credentials Binding Plugin UserName Password - chaitanyavangalapudi/devops-scripts GitHub Wiki

Credentials configured in Jenkins can be handled in Pipelines for immediate use. Jenkins' declarative Pipeline syntax has the credentials() helper method (used within the environment directive) which supports secret text, username and password, as well as secret file credentials. Here we will discuss about how to handle USERNAME & PASSWORD type of credentials.

Usernames and passwords

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

Example pipeline:

pipeline {
    agent any

    environment {
        USER_CREDENTIALS = credentials('TEST_CREDENTIAL')
        USER_CREDENTIALS_USER = "${env.USER_CREDENTIALS_USR}"
        USER_CREDENTIALS_PASSWORD = "${env.USER_CREDENTIALS_PSW}"
    }

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

        }
    }
}

this actually sets the following three environment variables:

  • USER_CREDENTIALS - contains a username and a password separated by a colon in the format username:password.
  • USER_CREDENTIALS_USR - an additional variable containing the username component only.
  • USER_CREDENTIALS_PSW - an additional variable containing the password component only.

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

  • Note1: To maintain the security and anonymity of these credentials, if you attempt to retrieve the value of these credential variables from within the Pipeline (e.g. echo $USER_CREDENTIALS_PSW), Jenkins only returns the value “” to prevent secret information from being written to the console output and any logs. Any sensitive information in credential IDs themselves (such as usernames) are also returned as “” in the Pipeline run’s output.

  • Note2: In this Pipeline example, the credentials assigned to the three USER_CREDENTIALS​ environment variables are scoped to global pipeline block, so these credential variables are available for use in this Run2 stage’s steps. If, however, the environment directive in this Pipeline were moved immediately within a stage block , then these USER_CREDENTIALS environment variables would be scoped local to that stage and can NOT be used in any other stage’s steps

  • Note3: Other types of credentials are handled using withCredentials method as discussed in the Jenkins reference manual.


References: