簡體   English   中英

如何使用 Jenkins Groovy 腳本中的憑據以編程方式調用 Git?

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

我的任務與此處描述的任務相似:
使用指定存儲庫中的 Git 分支動態填充 Jenkins 選擇參數

基本上,我想從 Jenkins Groovy 腳本中的遠程存儲庫中獲取標簽。

但問題是,我的存儲庫需要憑據才能訪問它們 - SSH 密鑰,這些密鑰存儲在 Jenkins 的憑據存儲中。

使用 Credentials 插件,您可以將您的憑證作為環境變量注入到您的工作中。 在 Jenkins 工作 DSL 插件中,它被稱為憑據綁定。 您可以將憑據存儲在 2 個單獨的變量中。

根據憑據的類型,這里有一個 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/

檢查一下,它可能會在沒有腳本的情況下為您提供所需的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM