Jenkins Pipeline 使用 Token 拉取 GitHub 儲存庫

在 Jenkinsfile 中拉取 git 專案是很基本的動作,不過筆者之前都是透過 SSH 驗證,現在有個需求是要使用 github token 的方式存取遠端儲存庫,遇到了一些小問題,特此紀錄一下。

在 Jenkins 中可以安裝 Git 這個套件,可以讓我們再 Pipeline 中很方便的存取 git 儲存庫,先安裝好,我們等等會使用到她。

Jenkinsfile 讀取 Jenkins 憑證(Credentials)裡的機密內容(密碼字串) 這篇中筆者示範了建立機密內容,我們這裡要示範使用 GitHub Token 來登入,先依照這篇的內容建立「Username with password」的機密內容,本文中的 ID 設定為 my_github_token ,方便辨識。使用者帳號填入 github 帳號,密碼填入 Token。不能建立其他的類型,包含 Secret text 等都不行, Jenkins Git 套件只支援這種和 SSH 金鑰,不然會讀不到。筆者在這裡嘗試了很久,最後去看了官方文件才發現...

接下來就是撰寫 Jenkinsfile 了,下面就是一個最簡單的示範,checkout scmGit 是 Jenkins Git 套件的語法,他幫我們解決了大多數的問題,只要指定好分支(這裡是 master),還有上面建立的機密內容 ID(這裡是 my_github_token),最後再加上遠端儲存庫的 URL 即可(這裡是 git@github.com:ruyut/report.git)
    
pipeline {
    stages {
        stage('git pull') {
            steps {
                checkout scmGit(
                    branches: [[name: '*/master']],
                    userRemoteConfigs: [[credentialsId: "my_github_token", url: "git@github.com:ruyut/report.git"]]
                )
            }
        }
    }
}

    

執行成功範例輸出:
    
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (git pull)
[Pipeline] checkout
The recommended git tool is: NONE
using credential my_github_token
 > git rev-parse --resolve-git-dir /var/jenkins_home/workspace/report/.git # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url git@github.com:ruyut/report.git # timeout=10
Fetching upstream changes from git@github.com:ruyut/report.git
 > git --version # timeout=10
 > git --version # 'git version 2.30.2'
using GIT_ASKPASS to set credentials 
 > git fetch --tags --force --progress -- git@github.com:ruyut/report.git +refs/heads/*:refs/remotes/origin/* # timeout=10
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
Checking out Revision c9d39b93cbad82cc89c8e0945eefb680f148a540 (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f c9d39b93cbad82cc89c8e0945eefb680f148a540 # timeout=10
Commit message: "feat: add Jenkinsfile"
 > git rev-list --no-walk 311388650bda277c3960825c44aa522d98e82500 # timeout=10
[Pipeline] }
    



參考資料:
Jenkins.plugins - git

留言