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.
More on Jenkins
What is Jenkins and how is its architecture organised?BeginnerWhat are executors, nodes and labels in Jenkins?IntermediateWhy should you not run builds on the Jenkins controller?BeginnerHow do inbound (JNLP/WebSocket) and SSH agents connect to the controller?IntermediateWhat is a Jenkinsfile and where does it live?BeginnerDeclarative versus Scripted Pipeline: what are the differences?Intermediate