Using Secrets in Pipelines
Reference stored credentials in a pipeline with credentials() or withCredentials so they stay masked.
environment { TOKEN = credentials('api-token') }There are two main ways to use a stored secret inside a pipeline. Both keep the value masked in the console log.
1. The environment directive
Assign credentials('id') to an environment variable. For a username/password credential, Jenkins also creates VAR_USR and VAR_PSW variants.
2. The withCredentials block
Wrap only the steps that need the secret in a withCredentials block. The variables exist just inside that block, which is more precise.
Example
pipeline {
agent any
stages {
stage('Deploy') {
steps {
withCredentials([usernamePassword(
credentialsId: 'dockerhub-login',
usernameVariable: 'DOCKER_USER',
passwordVariable: 'DOCKER_PASS'
)]) {
sh 'echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin'
sh 'docker push myuser/myapp:latest'
}
}
}
}
}When to use it
- A pipeline binds an AWS secret-access-key credential with withCredentials so it is masked in all log output.
- A Kubernetes deployment script reads a kubeconfig file credential that Jenkins writes to a temp file for the duration of the step.
- A team uses a username/password credential binding so the Nexus password never appears in the Jenkinsfile or build log.
More examples
withCredentials secret text binding
Injects a secret string into a masked env var for the duration of the withCredentials block only.
stage('Deploy') {
steps {
withCredentials([string(credentialsId: 'aws-secret-key',
variable: 'AWS_SECRET')]) {
sh 'aws configure set aws_secret_access_key $AWS_SECRET'
sh 'aws s3 sync dist/ s3://my-bucket/'
}
}
}Username and password binding
Binds a username/password credential pair to two separate masked environment variables for Maven deployment.
steps {
withCredentials([usernamePassword(
credentialsId: 'nexus-creds',
usernameVariable: 'NEXUS_USER',
passwordVariable: 'NEXUS_PASS'
)]) {
sh 'mvn deploy -s settings.xml -Dnexus.user=$NEXUS_USER -Dnexus.pass=$NEXUS_PASS'
}
}SSH key file binding
Writes an SSH private key to a temporary file and binds its path to SSH_KEY for a secure remote deploy.
steps {
withCredentials([sshUserPrivateKey(
credentialsId: 'deploy-server-key',
keyFileVariable: 'SSH_KEY',
usernameVariable: 'SSH_USER'
)]) {
sh 'ssh -i $SSH_KEY [email protected] ./deploy.sh'
}
}
Discussion