First of all we need to add the secret to the Jenkins Credentials management system. To do so, navigate through the menus to section
Jenkins > Credentials > System > Global credentials (unrestricted) > Add credentials
Then select the kind of secret that you need and specify its value. See an example in the next image:
It's important to know that this example uses a Jenkins declarative pipeline.
To load the contents of the secret we just need to use the function credentials(name_of_secret)
.
Then, it can be assigned to any variable that can be used later on any stage.
Here is an example below where we use a secret to handle a Codacy token of a Python project:
pipeline{
agent any
environment {
CODACY_TOKEN = credentials('etl-pipelines-codacy-token')
...
}
stages{
...
stage("Execute codacy"){
steps{
sh "export CODACY_PROJECT_TOKEN=${CODACY_TOKEN};python-codacy-coverage -r coverage.xml"
}
}
...
}
}
There you go, now you are correctly injection secrets to your Jenkins pipelines!