Jenkinsfile · Lesson 5 of 10 · 3 min read
Credentials, environment and parameters in practice
Binding credentials
withCredentials([
usernamePassword(credentialsId: 'ecr-pusher', usernameVariable: 'U', passwordVariable: 'P'),
string(credentialsId: 'slack-webhook', variable: 'SLACK_URL'),
file(credentialsId: 'prod-kubeconfig', variable: 'KUBECONFIG'),
sshUserPrivateKey(credentialsId: 'gitops-deploy-key', keyFileVariable: 'SSH_KEY')
]) {
sh '''
echo "$P" | docker login -u "$U" --password-stdin "$REGISTRY"
GIT_SSH_COMMAND="ssh -i $SSH_KEY -o StrictHostKeyChecking=accept-new" git push origin HEAD:main
'''
}
- Secrets are masked in logs, but never
echothem, write them to files you archive, or pass them via Groovy interpolation. - Prefer no stored cloud keys: IRSA/Pod Identity on Kubernetes agents, instance profiles, or
withAWS(role: ...)role assumption. - Scope credentials to the folder of the team that needs them.
Setting and passing values between stages
stage('Version') {
steps {
script {
env.VERSION = sh(script: 'git describe --tags --always', returnStdout: true).trim()
}
}
}
stage('Use it') { steps { echo "Version is ${env.VERSION}" } }
env.X set in a script block persists for the rest of the run. Locals declared with def inside script {} don't survive outside it. For values needed on another agent, also consider writing a file and stashing it.
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.
withEnv
withEnv(["MAVEN_OPTS=-Xmx1g", "SPRING_PROFILES_ACTIVE=ci"]) { sh 'mvn -B verify' }