Deploying and publishing need secrets, and Jenkins pipelines leak them easily if you bind or quote them wrong.
environment { } at the pipeline or stage level sets variables for the steps inside it. Values can be strings or helper calls.
Secrets live in the Credentials store (Manage Jenkins, Credentials, or a folder's credentials), each with an ID. Types include secret text, username with password, SSH private key and secret file. Two ways to use them:
- In
environment:TOKEN = credentials('api-token'). For username/password credentials Jenkins also definesNAME_USRandNAME_PSW. For secret files the variable holds a temporary path. - The
withCredentials([...]) { }step binds them only for a block, with bindings likestring,usernamePassword,fileandsshUserPrivateKey.
Jenkins masks bound secret values in the console log. The crucial rule: reference secrets with single quotes so the shell expands them, sh 'curl -H "Authorization: Bearer $TOKEN" ...'. With double quotes Groovy interpolates the secret into the command string, where it can appear in process listings and logs; Jenkins warns about this as insecure interpolation.
Scope credentials narrowly: put them in the folder of the jobs that need them instead of globally, so other teams' pipelines can't read them.
Example
pipeline {
agent any
environment {
APP = 'shop'
REGISTRY = credentials('registry-login') // also REGISTRY_USR / REGISTRY_PSW
}
stages {
stage('Publish') {
steps {
// single quotes: the shell expands the secret, not Groovy
sh 'echo "$REGISTRY_PSW" | docker login -u "$REGISTRY_USR" --password-stdin registry.example.com'
withCredentials([string(credentialsId: 'slack-token', variable: 'SLACK')]) {
sh 'curl -sf -H "Authorization: Bearer $SLACK" https://slack.example/api'
}
echo "Published ${APP}" // fine: not a secret
}
}
}
}Remember
- environment {} sets variables; credentials('id') binds a stored secret
- Username/password bindings add _USR and _PSW
- Always reference secrets inside single-quoted sh strings
Watch out for
- sh "curl -u $USER:$PASS ..." with double quotes interpolates secrets in Groovy, exposing them.