0
0
JenkinsHow-ToBeginner · 3 min read

How to Use withCredentials in Jenkins Pipeline

Use the withCredentials step in Jenkins Pipeline to securely access stored credentials inside a block. Wrap the code that needs the credentials within withCredentials, specifying the credential type and variable names to use them safely.
📐

Syntax

The withCredentials step wraps a block of code where credentials are temporarily available as environment variables. You specify the credential type and the variable names to hold the secret values.

  • credentials: The type and ID of the stored credential.
  • variable names: Environment variables to access the credentials inside the block.
  • block: The code that uses the credentials securely.
groovy
withCredentials([usernamePassword(credentialsId: 'my-cred-id', usernameVariable: 'USER', passwordVariable: 'PASS')]) {
    // Commands using $USER and $PASS
}
💻

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 myuser Password is mypassword
⚠️

Common Pitfalls

  • Not wrapping the code that uses credentials inside withCredentials causes secrets to be unavailable.
  • Exposing credentials by printing them directly in logs without masking.
  • Using wrong variable names or credential IDs causes errors or empty values.
  • Forgetting to add credentials in Jenkins Credentials Manager before referencing them.
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 TypeUsage ExampleVariables
usernamePasswordusernamePassword(credentialsId: 'id', usernameVariable: 'USER', passwordVariable: 'PASS')USER, PASS
stringstring(credentialsId: 'id', variable: 'TOKEN')TOKEN
filefile(credentialsId: 'id', variable: 'FILE')FILE

Key Takeaways

Always wrap credential usage inside the withCredentials block to access secrets securely.
Use correct credential IDs and variable names matching your Jenkins credentials setup.
Avoid printing sensitive credentials directly to logs to keep them safe.
withCredentials supports multiple credential types like usernamePassword, string, and file.
Add credentials in Jenkins Credentials Manager before referencing them in pipelines.