JamesD
JamesD

Reputation: 2546

How to get 'pipeline script from SCM' crendentials in pipeline script

Internally I'm transferring jobs from one Jenkins server to another, but I've wondered this when we need to change the permission on a job.

The option to check out from SCM has some credentials in it, shown in the image:

enter image description here

Is there a way to get the SCM checkout credentials from what is specified in the GUI level of the job, so i don't have to hard code the credential ID in the script.

Currently we have to sync the credential ID's ? This is annoying and error prone.

I've tried the normal GIt Plugin Environmental Vars but to no avail.

Upvotes: 1

Views: 1624

Answers (3)

rafaelrezend
rafaelrezend

Reputation: 1025

Is there a way to get the SCM checkout credentials from what is specified in the GUI level of the job, so i don't have to hard code the credential ID in the script.

Yes. If you are using Pipeline script from SCM, you can get the Credentials ID with the following snippet:

scm.getUserRemoteConfigs()[0].getCredentialsId()

This is useful, for example, when you want to dynamically checkout a Jenkins Library using the same credentials you configure in the Pipeline script from SCM GUI.

library identifier: 'sample-jenkins-library@master', retriever: modernSCM(
        [$class: 'GitSCMSource',
        remote: 'https://github.com/repo/sample-jenkins-library.git',
        credentialsId: scm.getUserRemoteConfigs()[0].getCredentialsId()])

Please keep in mind that libs loaded this way aren't considered trusted. Not exactly part of the question, but very valuable info if you got here with the intention of implementing exactly that!

Upvotes: 2

Rob Hales
Rob Hales

Reputation: 5321

You could just migrate all the credentials from the old Jenkins instance to the new one before you start configuring the jobs. Then delete what you don't use later, if needed.

https://support.cloudbees.com/hc/en-us/articles/115001634268-How-to-migrate-credentials-to-a-new-Jenkins-instance-

Upvotes: 0

Dan Wilson
Dan Wilson

Reputation: 4047

It's not possible to get the library credentials ID within the pipeline script.

The best you can do is get the version (branch name) for the library. For example, env.getProperty("library.<NAME>.version") where <NAME> is the name of your shared library.

I had to migrate jobs to a new Jenkins instance and ran into this same issue. The only silver lining is that I now reference credential IDs using string constants where possible so that future updates are simple.

Job migration is a tedious process, and managing credentials can be difficult. Once you have many credentials defined it can be a challenge.

Upvotes: 0

Related Questions