jenkinshudsonjenkins-pluginshudson-pluginshudson-api

Get Project's Credentials using Jenkins API


I'm building a Jenkins plugin that one of the features is to commit and push some files generated during the build. I already have the code to commit and to push (using Git client from org.jenkinsci.plugins), however when I execute

PushCommand push = gitClient.push();
push.ref(__MY_BRANCH__);
push.to(new URIish("origin"))
push.force();
push.execute();

I get an error not having permissions to push. So, my question is: how can I re-use the credentials of a project to proper configue gitClient or the pushCommand ?

-- Thanks, Jose


Solution

  • You need to provide credentials to the GitClient.

    For example, here you can see the Git plugin calling the GitClient#addDefaultCredentials() method, using credentials obtained from CredentialsMatchers.

    You mention you want to re-use the credentials from the same job so — assuming that the Git plugin has been configured with those credentials — your plugin should have access to the AbstractBuild where you can use something like build.getProject().getScm()​.getUserRemoteConfigs().get(0)​.getCredentialsId to fetch the configured credentials ID.

    You'll need to cast the SCM to GitSCM, but otherwise that should work fine.