如何以编程方式在Jenkins Groovy脚本中使用凭据调用Git?

时间:2016-09-29 21:24:04

标签: git jenkins groovy jenkins-plugins

我的任务类似于此处描述的任务:
Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

基本上,我想从Jenkins Groovy脚本中的远程存储库中获取标签。

但问题是,我的存储库需要凭据才能访问它们 - SSH密钥,存储在Jenkins的凭据存储中。

2 个答案:

答案 0 :(得分:0)

使用Credentials插件,您可以将凭据作为环境变量注入作业。在Jenkins作业DSL插件中,它被称为凭证绑定。您可以将凭据存储在2个单独的变量中。

答案 1 :(得分:0)

根据凭据的类型,这里有一个 groovy 脚本,用于获取可与 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
    }
}

然后连接到 git 并获取标签,例如:

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")

我想用带有 -key 参数和 SSH var 的 ssh 密钥来尝试这个,但它没有用,但我偶然发现: https://plugins.jenkins.io/git-parameter/

检查一下,它可能无需编写脚本即可满足您的需求。