【 Gitlab】使用service account token
當有多個 Service Account (例如不同專案、不同環境或不同部門權限分立) 時,有兩種標準架構可做到精確隔離、不互相覆蓋且不影響本地 Global 設定:
方法一:單一憑證檔多路徑匹配 (推薦,管理最集中)
Git 支援在同一個憑證檔中,依據 完整 URL 路徑 (包含 Group/Project) 匹配對應的 Service Account 帳密。
1. 在憑證檔中條列各專案路徑與對應 Token
在中繼機上建立或編輯憑證檔:
cat << 'EOF' > /root/.git-credentials-multi-sa
# 專案 A (使用 SA 1)
https://<SA_1_USER>:<SA_1_TOKEN>@gitlab.com/group-a/safety-deploy.git
https://<SA_1_USER>:<SA_1_TOKEN>@gitlab.com/group-a/safety-app-integrity.git
# 專案 B (使用 SA 2)
https://<SA_2_USER>:<SA_2_TOKEN>@gitlab.com/group-b/other-project.git
# 專案 C (使用 SA 3)
https://<SA_3_USER>:<SA_3_TOKEN>@gitlab.com/payment-team/payment-service.git
EOF
chmod 600 /root/.git-credentials-multi-sa
2. Clone 時啟用 credential.useHttpPath
為了讓 Git 依據「完整 URL 路徑」而不僅僅是「Domain (gitlab.com)」來精確選取對應的 Service Account,需在 Clone 時帶入
credential.useHttpPath=true:# Clone 專案 A (自動匹配 SA 1)
git -c credential.useHttpPath=true \
-c credential.helper="store --file /root/.git-credentials-multi-sa" \
clone -b master https://gitlab.com/group-a/safety-deploy.git
# 進入專案綁定 Local 設定 (避免後續 fetch/pull 找不到)
cd safety-deploy
git config --local credential.useHttpPath true
git config --local credential.helper "store --file /root/.git-credentials-multi-sa"
方法二:多憑證檔獨立切分 (適合完全隔離或環境劃分)
若各個 Service Account 歸屬不同業務線或環境,可為各 Service Account 建立獨立的憑證檔。
1. 建立獨立檔案
Bash
# Team A / Safety 專用
echo "https://<SA_SAFETY_USER>:<SA_SAFETY_TOKEN>@gitlab.com" > /root/.git-credentials-sa-safety
chmod 600 /root/.git-credentials-sa-safety
# Team B / Core 專用
echo "https://<SA_CORE_USER>:<SA_CORE_TOKEN>@gitlab.com" > /root/.git-credentials-sa-core
chmod 600 /root/.git-credentials-sa-core
2. 在各自的流程中指定特定檔案 Clone
在對應專案的建置腳本中,單獨指向該專屬檔案:
# 部署 Safety 專案時
git -c credential.helper="store --file /root/.git-credentials-sa-safety" \
clone -b master https://gitlab.com/group-a/safety-deploy.git
# 部署 Core 專案時
git -c credential.helper="store --file /root/.git-credentials-sa-core" \
clone -b master https://gitlab.com/group-b/core-service.git
# 關鍵步驟:將 helper 固化寫入該專案的 .git/config 這樣git pull 才不會要你打密碼
cd core-service
git config --local credential.helper "store --file /root/.git-credentials-sa-core"
# 一鍵處理
# Clone 並在成功後直接寫入 Local 設定
git -c credential.helper="store --file /root/.git-credentials-sa-core" \
clone -b master https://gitlab.com/group-b/core-service.git && \
git -C core-service config --local credential.helper "store --file /root/.git-credentials-sa-core"
方案比較
| 特性 | 方法一:單一憑證檔 + useHttpPath | 方法二:獨立憑證檔切分 |
| 檔案管理 | 集中管理於單一檔案 (multi-sa) |
各 Service Account 獨立檔案 |
| 權限匹配 | 依據 Group / Project 路徑自動路由 | 依據腳本執行的命令手動指定路徑 |
| 維護成本 | 新增專案只需在該檔案追加一行 | 新增專案需維護新檔案路徑 |
| 適用場景 | 同一環境需存取多個不同權限的專案 | 不同團隊或 Pipeline 需實體隔離設定檔 |