Credentials without hardcoding secrets

Jenkins CI/CD Course · lesson 7 of 15 · 5 min read

A Jenkinsfile should name a credential id and never contain the secret behind it.

Open this lesson in the learning hub

Key points

  • Credentials live in the Jenkins credentials store, and a pipeline refers to one only by its id.
  • withCredentials binds a secret into a variable for one block and unbinds it when the block ends.
  • Binding a username and password pair in environment also creates _USR and _PSW variables.
  • Jenkins masks a bound secret in the console, but the mask only matches the exact string it bound.
  • Base64 or a substring of a secret prints in the clear, and set -x in a shell step dumps the whole command.
  • Folder scoped credentials keep one team secret invisible to jobs living in other folders.

Example

stage('Push image') {
  steps {
    withCredentials([usernamePassword(credentialsId: 'registry-creds',
                                      usernameVariable: 'REG_USER',
                                      passwordVariable: 'REG_PASS')]) {
      // --password-stdin: the secret never becomes a process argument
      sh '''
        set +x
        echo "$REG_PASS" | docker login registry.example.com \
             -u "$REG_USER" --password-stdin
        docker push "$IMAGE"
      '''
    }
  }
}

A Jenkinsfile should contain credential ids only, and a leaked secret is revoked before it is tidied up.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Jenkins CI/CD Course course, and every lesson in it is listed on the Jenkins CI/CD Course contents page.