Credentials without hardcoding secrets
A Jenkinsfile should name a credential id and never contain the secret behind it.
Open this lesson in the learning hubKey points
- Credentials live in the Jenkins credentials store, and a pipeline refers to one only by its id.
withCredentialsbinds a secret into a variable for one block and unbinds it when the block ends.- Binding a username and password pair in
environmentalso creates_USRand_PSWvariables. - Jenkins masks a bound secret in the console, but the mask only matches the exact string it bound.
- Base64 or a substring of a secret prints in the clear, and
set -xin a shell step dumps the whole command. - Folder scoped credentials keep one team secret invisible to jobs living in other folders.
Example
stage('Push image') {
steps {
withCredentials([usernamePassword(credentialsId: 'registry-creds',
usernameVariable: 'REG_USER',
passwordVariable: 'REG_PASS')]) {
// --password-stdin: the secret never becomes a process argument
sh '''
set +x
echo "$REG_PASS" | docker login registry.example.com \
-u "$REG_USER" --password-stdin
docker push "$IMAGE"
'''
}
}
}
A Jenkinsfile should contain credential ids only, and a leaked secret is revoked before it is tidied up.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Jenkins CI/CD Course course, and every lesson in it is listed on the Jenkins CI/CD Course contents page.