GitSCM credentials programmatically with Groovy

Viewed 184

How can I pass the credential information when creating a job based on a Jenkinsfile in GitHub?

#!groovy
import hudson.*
import jenkins.*
import jenkins.model.*
import hudson.model.*
import hudson.plugins.git.*;
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.*

// Creating the credential to access GitHub
def parent = Jenkins.instance
def source = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource("HIDDEN")
def ck1 = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, "GitHub", "user", source, "password", "My Description")
SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), ck1)

// Creating the pipeline
def scm = new GitSCM("ssh-url")
scm.branches = [new BranchSpec("*/main")]
def flowDefinition = new org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition(scm, "Jenkinsfile")
def job = new org.jenkinsci.plugins.workflow.job.WorkflowJob(parent, "Dev-1")
job.definition = flowDefinition
parent.save()
parent.reload()

The result when I run it is the following:

stderr: git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
0 Answers
Related