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>_USRand<VAR>_PSWhelper vars. - Jenkins masks credential values in logs, but
set -xor echoing them can still leak; avoid printing secrets. - Use
withCredentialsto scope a secret to a narrow block instead of the whole pipeline.
Key takeaways
credentials()inenvironment {}binds a secret to an env var.withCredentialsscopes typed secrets to a block.- Values are masked, but never echo them yourself.
Related guides
How to Use Secrets in a Jenkins PipelineUse secrets in a Jenkins pipeline with the Credentials plugin - the credentials() helper, withCredentials bin…
How to Use Parameters in a Jenkins PipelineUse the parameters block in a Jenkins declarative pipeline to add a Build with Parameters form with string, c…