简体   繁体   中英

How to programmatically invoke Git with credentials in Jenkins Groovy script?

My task is similar to the one, described here:
Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

Basically, I want to fetch tags from a remote repositories within Jenkins Groovy script.

But the problem is, that my repositories require credentials for accessing them - SSH keys, which are stored in credentials storage of Jenkins.

Using the Credentials plugin you can inject your credentials as environment variables to your job. In Jenkins job DSL plugin it's called credentials binding. You can have the Credentials stored in 2 separate variables.

depending on what type of credentials, here is a groovy script to get username and password for credentials storage that can be used with https://plugins.jenkins.io/extensible-choice-parameter/ :

def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
    com.cloudbees.plugins.credentials.Credentials.class,
    Jenkins.instance,
    null,
    null
);

def username
def password

for (creds in jenkinsCredentials) {
  if(creds.id == "user-pass-id-in-jenkins-cred-storage"){
    username = creds.username
    password = creds.password
    }
}

then to connect to git and get tags, something like :

def command = [ "/bin/bash", "-c", "git ls-remote --tags https://$username:$password@yourgit.domain/path/repo.git | awk '{print \$2}' | sort -r -V | sed 's@refs/tags/@@'" ]
def process = command.execute();
process.waitFor()

def result = process.text.tokenize("\n")

I was looking to try this with an ssh key with -key parameter and SSH var, but it did not work, but I stumbled upon: https://plugins.jenkins.io/git-parameter/

Check it out, it probably gives you what you need without scripting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM