How to Use withCredentials Step in Jenkins Pipelines
Use the
withCredentials step in Jenkins pipelines to securely access stored credentials by wrapping the code that needs them. It temporarily injects credentials as environment variables or files, ensuring secrets are not exposed in logs or code.Syntax
The withCredentials step wraps a block of code where credentials are needed. You specify the credential type and ID, then assign environment variable names to use inside the block.
Common credential types include usernamePassword, string, and file.
groovy
withCredentials([usernamePassword(credentialsId: 'my-cred-id', usernameVariable: 'USER', passwordVariable: 'PASS')]) { // Commands using USER and PASS environment variables }
Example
This example shows how to use withCredentials to access a username and password stored in Jenkins credentials. The credentials are injected as environment variables USER and PASS inside the block.
groovy
pipeline {
agent any
stages {
stage('Use Credentials') {
steps {
withCredentials([usernamePassword(credentialsId: 'my-cred-id', usernameVariable: 'USER', passwordVariable: 'PASS')]) {
sh 'echo Username is $USER'
sh 'echo Password is $PASS'
}
}
}
}
}Output
Username is myUsername
Password is myPassword
Common Pitfalls
- Not wrapping the code that uses credentials inside
withCredentialscauses environment variables to be undefined. - Exposing credentials by printing them directly in logs is unsafe; avoid
echoof passwords in real pipelines. - Using wrong
credentialsIdor variable names leads to errors or empty values.
groovy
/* Wrong way: credentials used outside withCredentials block */ sh 'echo $USER' /* Right way: credentials used inside withCredentials block */ withCredentials([usernamePassword(credentialsId: 'my-cred-id', usernameVariable: 'USER', passwordVariable: 'PASS')]) { sh 'echo $USER' }
Quick Reference
| Credential Type | Usage Example | Injected 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 wrap code that uses secrets inside the withCredentials block to access them safely.
Use the correct credential type and variable names matching your Jenkins credentials setup.
Never print sensitive credentials directly in logs to avoid security risks.
withCredentials temporarily injects secrets as environment variables or files only inside its block.
Check your credentialsId carefully to avoid errors or missing values.