How do you use credentials in a Jenkinsfile safely?

IntermediateConceptJenkins
Answer

Store secrets in the Jenkins Credentials store (types: Secret text, Username with password, SSH key, Secret file, Certificate) and bind them at runtime with credentials() in environment or withCredentials. Jenkins masks bound values in the console log.

environment { AWS = credentials('aws-deploy') }   // sets AWS_USR and AWS_PSW
steps {
  withCredentials([string(credentialsId: 'sonar-token', variable: 'SONAR_TOKEN')]) {
    sh 'mvn sonar:sonar -Dsonar.token=$SONAR_TOKEN'
  }
}

Use single quotes for sh so the shell expands the variable, not Groovy. Groovy string interpolation of secrets leaks them into the process list and warnings.

All CI/CD questions

More on Jenkins