Answer
Managing Credentials in Jenkins
Never hardcode passwords or tokens in Jenkinsfiles. Use Jenkins' built-in Credentials Manager.
Adding Credentials in Jenkins UI
- ✓Jenkins → Manage Jenkins → Credentials
- ✓Select scope: Global (recommended) or specific folder
- ✓Click Add Credentials
- ✓Choose type:
- ✓Username with password (DB creds, GitHub HTTPS)
- ✓SSH Username with private key (server access)
- ✓Secret text (API tokens, API keys)
- ✓Secret file (service account JSON, .p12 files)
- ✓Certificate (PKCS#12)
Using Credentials in Declarative Pipeline
GROOVY
pipeline {
agent any
environment {
// Binds credential to env vars (username + password)
DOCKER_CREDS = credentials('docker-hub-credentials')
// Creates: DOCKER_CREDS_USR and DOCKER_CREDS_PSW
}
stages {
stage('Docker Login') {
steps {
sh 'echo $DOCKER_CREDS_PSW | docker login -u $DOCKER_CREDS_USR --password-stdin'
}
}
stage('API Tests') {
steps {
// Secret text — bound to single variable
withCredentials([string(credentialsId: 'api-key', variable: 'API_KEY')]) {
sh 'mvn test -Dapi.key=${API_KEY}'
}
}
}
stage('Deploy via SSH') {
steps {
withCredentials([
sshUserPrivateKey(
credentialsId: 'prod-server-ssh',
keyFileVariable: 'SSH_KEY',
usernameVariable: 'SSH_USER'
)
]) {
sh 'ssh -i $SSH_KEY $SSH_USER@prod.server.com "./deploy.sh"'
}
}
}
stage('Use Secret File') {
steps {
withCredentials([file(credentialsId: 'gcp-service-account', variable: 'GCP_JSON')]) {
sh 'gcloud auth activate-service-account --key-file=$GCP_JSON'
}
}
}
}
}
Credentials in Shared Libraries
GROOVY
// vars/deployToK8s.groovy
def call(String environment) {
withCredentials([
string(credentialsId: "k8s-token-${environment}", variable: 'K8S_TOKEN')
]) {
sh "kubectl --token=$K8S_TOKEN apply -f k8s/${environment}/"
}
}
Jenkins Credentials as Environment Variables
GROOVY
environment {
GITHUB_TOKEN = credentials('github-pat') // secret text
SONAR_TOKEN = credentials('sonarqube-token') // secret text
DB_CREDENTIALS = credentials('db-username-password') // user+pass
// DB_CREDENTIALS_USR = username
// DB_CREDENTIALS_PSW = password
}
Best Practices
- ✓Use Folder-scoped credentials to limit access per project
- ✓Rotate credentials regularly
- ✓Use HashiCorp Vault plugin for enterprise secret management
- ✓Never
echoorprintcredential variables in logs - ✓Jenkins masks credential values in build output automatically
