Secret text in Jenkinsfile scripted pipelines

Scripted pipelines are great for using Jenkinsfile but Jenkins’ documentation doesn’t tell how to use credentials with them. And trying to use the credentials function listed there won’t work.

In short, this is what does work:

  1. First setup your secret text in the Credentials category like so (if you don’t have the credentials category make sure you have the Credentials plugin installed and enabled):

    1. Open the credentials category:

      Open credentials

    2. Add new credentials:

      Add new credentials

    3. Enter the info and confirm:

      Enter the info and confirm

  1. Then in your Jenkinsfile use the following:
1
2
3
4
5
node {
withCredentials([string(credentialsId: 'my-secret', variable: 'SECRET') { //set SECRET with the credential content
echo "My secret text is '${SECRET}'"
}
}

Output:

My password is '****'