How to Use Credentials in Jenkins Pipeline
In Jenkins Pipeline, use the
credentials() function inside a withCredentials block to securely access stored credentials. This allows you to inject secrets like usernames, passwords, or tokens into your pipeline steps without exposing them in logs.Syntax
The withCredentials block wraps the code that needs access to credentials. You specify the credential type and ID, then assign them to environment variables for use inside the block.
Common credential types include usernamePassword, string, and file.
groovy
withCredentials([usernamePassword(credentialsId: 'my-cred-id', usernameVariable: 'USER', passwordVariable: 'PASS')]) { // Use USER and PASS variables here sh 'echo Username is $USER' }
Example
This example shows how to use a username and password stored in Jenkins credentials inside a pipeline to authenticate a Git command.
groovy
pipeline {
agent any
stages {
stage('Use Credentials') {
steps {
withCredentials([usernamePassword(credentialsId: 'git-credentials', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PASS')]) {
sh 'git clone https://$GIT_USER:$GIT_PASS@github.com/example/repo.git'
}
}
}
}
}Output
Cloning into 'repo'...
remote: Enumerating objects: 10, done.
remote: Counting objects: 100% (10/10), done.
remote: Compressing objects: 100% (8/8), done.
Receiving objects: 100% (10/10), done.
Common Pitfalls
- Not wrapping credential usage inside
withCredentialscauses secrets to be exposed in logs. - Using wrong
credentialsIdwill fail silently or cause authentication errors. - Forgetting to use the environment variables inside the block results in empty or missing values.
groovy
/* Wrong way: Using credentials without withCredentials block */ sh 'echo $MY_SECRET' /* Right way: Wrap usage inside withCredentials */ withCredentials([string(credentialsId: 'my-secret-id', variable: 'MY_SECRET')]) { sh 'echo $MY_SECRET' }
Quick Reference
| Credential Type | Usage Example | Environment Variables |
|---|---|---|
| usernamePassword | usernamePassword(credentialsId: 'id', usernameVariable: 'USER', passwordVariable: 'PASS') | USER, PASS |
| string | string(credentialsId: 'id', variable: 'TOKEN') | TOKEN |
| file | file(credentialsId: 'id', variable: 'FILE_PATH') | FILE_PATH |
Key Takeaways
Always use withCredentials block to securely access Jenkins credentials in pipelines.
Use the correct credentialsId matching the stored Jenkins credential.
Assign credentials to environment variables inside withCredentials for safe usage.
Never print or expose credentials outside the withCredentials block to avoid leaks.
Common credential types include usernamePassword, string, and file.