Skip to content
Latchkey

How to Use credentials() Binding in a Jenkins Pipeline

Jenkins injects stored secrets into a build with the credentials() helper in environment {} or a withCredentials block, masking them in logs.

Reference a credential by its ID. In environment {}, credentials() binds it to an env var; withCredentials scopes secrets to a block and supports typed bindings.

Bind a secret credential

The credential ID maps to an env var; Jenkins masks the value in console output.

Jenkinsfile
pipeline {
  agent any
  environment {
    API_TOKEN = credentials('prod-api-token')
  }
  stages {
    stage('Deploy') {
      steps {
        sh 'curl -H "Authorization: Bearer ${API_TOKEN}" https://api.example.com/deploy'
        withCredentials([usernamePassword(
          credentialsId: 'registry',
          usernameVariable: 'REG_USER',
          passwordVariable: 'REG_PASS')]) {
          sh 'echo ${REG_PASS} | docker login -u ${REG_USER} --password-stdin'
        }
      }
    }
  }
}

Gotchas

  • A username/password credential bound via credentials() also sets <VAR>_USR and <VAR>_PSW helper vars.
  • Jenkins masks credential values in logs, but set -x or echoing them can still leak; avoid printing secrets.
  • Use withCredentials to scope a secret to a narrow block instead of the whole pipeline.

Key takeaways

  • credentials() in environment {} binds a secret to an env var.
  • withCredentials scopes typed secrets to a block.
  • Values are masked, but never echo them yourself.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →