Opscraft
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 echo them, 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 diagramdef version = …env.VERSION = …Local to that script { } blockGone in the next stage"No such property" laterLives for the whole run${env.VERSION} in Groovy$VERSION in sh
Figure 1. Passing a value to a later stage. Only env.* survives the end of a script {} block.
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' }