Script To Retrieve Jenkins Credentials

Groovy Script To Retrieve Jenkins Credentials

Jenkins supports many credential type based on your needs. It could be a password, secret file, ssh private key or a token. There could be many use cases to use a groovy script to deal with credentials. Few use cases are

  1. You might want to create credentials in the run time.
  2. You might want to use a custom groovy code with Active choice parameters.
  3. You might want to extend your Jenkins shared library for a credential create functionality.

This tutorial explains how to get the stored credentials in Jenkins using a custom groovy script.

Script To Retrieve Jenkins Credentials

To retrieve Jenkins credentials, you should import cloudbees credentials specific libraries. And use the lookupCredentials function to get all the credentials store in Jenkins.

Here is the full groovy script to list all the Jenkins credentials.

You can test this script using the Jenkins script console.

Get a Specific Stored Credential

In the above example, we have seen how to list all the Jenkins credentials.

Let’s say you have a credential of type username and password and you want to retrieve those values using the script.

For this, you need to know the ID of the credential. For example, if you have a credential with an ID named user-pass. Here is how the for loop will look like to extract the username and password.

If you run the whole script you should get the following output.

jenkins groovy script credential output.

How To Find Credentials Type Variables

To retrieve the secrets, each credentials type has its own variables. It should be used in small letters.

For example, for username and password, you can use the following variables to retrieve the value.

As you can see in the above image, the variable which are present during credentials creation is what we use in the code in all small letters.

Let’s say in the same way you have a private key variable like shown below. In this case, the variable name will be privateKey

Here is code to retrive ssh key from id.


The Best Tutorials & Tips to Speedup Your DevOps Workflow.

Created by Bibin Wilson.