【GitLab】相關

【GitLab】gitlab-runner 執行環境種類

下面整理成表格給你(主流可用的 executor):

Executor 運作方式 優點 缺點 適用情境 設定/註冊要點
shell 直接在 Runner 主機的 shell 執行(bash / PowerShell) 最快、零容器開銷;可直接用主機已安裝工具 隔離最弱、容易「弄髒」主機;多專案易衝突 單機/內網、快速 smoke test、固定工具鏈 gitlab-runner register --executor shell;確保 gitlab-runner 使用者權限(如加入 docker 群組)與 builds_dir 可寫
docker 每個 job 以容器執行;image: 可指定環境 環境可重現、隔離佳、跨專案穩定 需管理映像;使用 Docker 需選擇掛 docker.sock 或 DinD 大多數 CI/CD 場景(前後端 build、容器化) --executor docker --docker-image <base>;若 job 需 docker build:① 掛 /var/run/docker.sock,或 ② DinD:privileged=true + services: docker:dind
kubernetes 每個 job 建一個 Pod 來跑 彈性擴縮、資源/隔離/配額完善 需 K8s 叢集與維運成本 中大型團隊、尖峰負載、雲原生 --executor kubernetes;於 config.toml 設 namespace、serviceAccount、pull secrets 等
ssh Runner 透過 SSH 登入遠端主機執行 可用現成遠端環境、無需在目標機器裝 Runner 隔離弱、擴展性差、權限管控要嚴格 特定機器/設備、臨時需求 --executor ssh;於 config.toml 填 host/user/key、路徑與環境
custom 以自訂腳本(prepare/run/cleanup)對接任意執行環境 彈性最高、可接非官方平台 需自寫與維護整套腳本,診斷較複雜 特殊平台、內部排程器 --executor custom;提供自訂 hook 腳本並測好錯誤處理

【GitLab】升級相關

升級路徑
https://gitlab-com.gitlab.io/support/toolbox/upgrade-path/

【GitLab】runner 使用 k8s 流程說明

 

一、前置條件


二、建立命名空間

kubectl create namespace gitlab-runner     # 放 Runner 本體
kubectl create namespace ci-jobs           # job 跑的位置(也可與上面同一 ns)

三、用 Helm 裝 Runner(K8s executor)

  1. 加入 chart

helm repo add gitlab https://charts.gitlab.io
helm repo update
  1. 建一份 values.yaml

gitlabUrl: "http://10.2.11.139/"
# 新流程建議用 runnerToken(glrt-...)
runnerToken: "glrt-xxxxxxxxxxxxxxxxxxxxxxxxxxxx"

rbac:
  create: true

serviceAccount:
  create: true
  name: gitlab-runner

runners:
  executor: kubernetes
  # job 要跑在哪個 ns;不填則跟 Runner 同 ns
  namespace: ci-jobs
  # 預設 job 容器用什麼 image(可被 .gitlab-ci.yml 的 image 覆蓋)
  image: alpine:3.20
  pollTimeout: 180

  # 是否允許特權容器(多數情況不需要,建議先關)
  privileged: false

  # 幫 job Pod 加上標籤(可選)
  podLabels:
    app: gitlab-ci-job

  # 預設資源限制(可選)
  resources:
    limits:
      cpu: "1"
      memory: "1Gi"
    requests:
      cpu: "200m"
      memory: "256Mi"

  # Cache(可選:接 S3/MinIO;此段示意,若未啟用請刪除)
  cache:
    type: s3
    path: "gitlab-runner"
    s3ServerAddress: "minio.minio.svc.cluster.local:9000"
    s3BucketName: "gitlab-ci-cache"
    s3AccessKey: "minio-access"
    s3SecretKey: "minio-secret"
    s3Secure: false

新流程下:tags / run-untagged / locked 等屬性建議在 GitLab UI 的 Runner 設定頁調整,不再用 CLI 參數寫入。

  1. 安裝

helm upgrade --install gitlab-runner gitlab/gitlab-runner \
  -n gitlab-runner -f values.yaml
  1. 驗證

kubectl -n gitlab-runner get pods
# 應看到 gitlab-runner 的 Pod(或 deployment/rs)

四、最小 .gitlab-ci.yml(驗證 K8s executor 正常)

stages: [ping]

hello:
  stage: ping
  image: alpine:3.20
  script:
    - echo "Runner: $CI_RUNNER_DESCRIPTION"
    - echo "Executor: Kubernetes OK"
    - cat /etc/os-release

跑起來時的 log 開頭應出現:Preparing the "kubernetes" executor
K8s 裡 ci-jobs 命名空間會看到對應的 Pod(生命周期:Running → Succeeded)。


五、在 K8s executor 內建 Docker 映像(推薦用 Kaniko)

K8s executor 不建議 DinD。常見做法是用 Kaniko(rootless,無需 Docker daemon)。

  1. 在 GitLab 專案 CI Variables 設定:

  1. Kaniko Job 範例

stages: [build]

docker-build:
  stage: build
  image:
    name: gcr.io/kaniko-project/executor:latest
    entrypoint: [""]
  variables:
    # registry 登入(若用 GitLab Container Registry,可改為 CI 提供的 token)
    DOCKER_CONFIG: /kaniko/.docker
  script:
    - >
      mkdir -p /kaniko/.docker &&
      cat > /kaniko/.docker/config.json <<EOF
      {
        "auths": {
          "${CI_REGISTRY}": {
            "auth": "$(printf "%s:%s" "$CI_REGISTRY_USER" "$CI_REGISTRY_PASSWORD" | base64 -w0)"
          }
        }
      }
      EOF
    - echo -e 'FROM alpine:3.20\nCMD ["echo","kaniko build OK"]' > Dockerfile
    - >
      /kaniko/executor
      --context "${CI_PROJECT_DIR}"
      --dockerfile "${CI_PROJECT_DIR}/Dockerfile"
      --destination "${CI_REGISTRY_IMAGE}:$CI_COMMIT_SHA"
      --destination "${CI_REGISTRY_IMAGE}:latest"

這個 job 會在 K8s 中跑 Kaniko,把映像打好推到 Registry,不需要 Docker daemon、也不需要 privileged。


六、(可選)Sidecar 服務示例(K8s 會幫你生多容器 Pod)

stages: [test]

pg-test:
  stage: test
  image: postgres:16-alpine
  services:
    - name: postgres:16-alpine
      alias: db
  variables:
    POSTGRES_PASSWORD: secret
  script:
    - psql -h db -U postgres -c "SELECT version();"

在 K8s executor 下,services: 會轉成 同一個 Pod 的 sidecar 容器,網路互通用 alias 連線。


七、常見疑難排解


八、如果不用 Helm(純手工方式,了解即可)

但維運上 Helm chart 會簡單很多(升級/回滾/佈署差異)。


需要我幫你把 values.yaml 客製到你的環境(例如 MinIO 位址、特定節點選擇器、Pod 安全性設定、預設資源)嗎?我可以直接產一份可用的版本給你。

【GitLab】CI/CD Settings 說明

✅  General pipelines

image-1755143476227.png


1. Public pipelines 


2. Auto-cancel redundant pipelines 


3. Skip outdated deployment jobs 


4. Use separate caches for protected branches 


5. CI/CD configuration file


6. Git strategy


7. Git shallow clone


8. Timeout


我看你的設定,Git strategy 用 fetch + shallow clone 20,這樣拉程式會比較快,但如果你有需要依賴完整 commit 歷史(例如 git describe、全量 tag 檢出),要把 shallow clone 設成 0

✅ Pipeline status

image-1755161177902.png

這張圖是 GitLab 專案的 CI/CD 狀態徽章(Badges)設定頁,它提供了一些可以放到 README 或網頁上的「狀態顯示圖示」,用來即時反映專案的 CI/CD 情況。

分三塊說明:


1. Pipeline status(流水線狀態)


2. Coverage report(測試覆蓋率)


3. Latest release(最新版本)


4. 使用方式


✅ Auto DevOps

image-1755163898687.png

你這張圖是 GitLab Auto DevOps 的設定頁面,它是 GitLab 提供的一套「自動化 CI/CD Pipeline」功能,讓專案在沒有自訂 .gitlab-ci.yml 的情況下,也能自動完成建置、測試、部署等流程。


1. Default to Auto DevOps pipeline


2. 提示訊息

Add a Kubernetes cluster integration with a domain, or create an AUTO_DEVOPS_PLATFORM_TARGET CI variable.

3. Deployment strategy(部署策略)

三種選項:

  1. Continuous deployment to production(持續部署到正式環境)

    • 每次 Pipeline 成功就會自動部署到 Production。

  2. Continuous deployment to production using timed incremental rollout(定時漸進式部署)

    • 部署會分批釋出,逐漸更新所有節點(需要 Kubernetes 支援)。

  3. Automatic deployment to staging, manual deployment to production(自動部署到測試環境,手動部署到正式環境)

    • 先自動部署到 Staging 環境,Production 需要手動觸發。


4. 總結影響


✅ Runners

image-1755165012676.png

 


1. Runners 概念


2. Specific runners

這個區塊是專屬於當前專案的 Runner。
圖片中有兩個 active 的 Runner:

Runner 名稱 類型 Tag 狀態
#347 (UgMp--WG) Docker Executor app-docker-204 🟢 active
#343 (Mw1g8wwh) Shell/VM Executor app-docker-vm-204 🟢 active

Tag 作用:


3. Runner 註冊方式

左邊「Set up a specific runner for a project」提供:


4. Shared runners


5. Group runners


6. 運作重點


✅ Artifacts

Uploaded image

這張圖是 GitLab 專案的 Artifact 保留設定



使用情境


 

這張圖是 GitLab CI/CD 專案層級的 Variables 設定頁面,主要是用來存放敏感資訊(例如密碼、金鑰、帳號等),在 Pipeline 中可以直接引用。


Variables(變數)

1. Variables(變數)


2. 欄位說明

欄位 說明
Type 一般都是 Variable,也可能是 File(將值存成檔案再提供給 Job)。
Key 變數名稱(例如 PassWdUserName),在 CI/CD job 中用 $PassWd 存取。
Value 變數值(已隱藏),只有有權限的使用者才能看到。
Protected ✅ 表示這個變數只會在 Protected branchProtected tag 的 pipeline 中被注入。
Masked ✅ 代表在 Job log 中會以 ***** 隱藏,防止外洩(必須符合 GitLab Mask 規則)。
Environments 變數適用的環境,例如 Allproductionstaging 等。

3. 圖中範例


4. 使用範例

假設你在 .gitlab-ci.yml 中要用這兩個變數:

stages:
  - test

show-vars:
  stage: test
  script:
    - echo "User: $UserName"
    - echo "Password: $PassWd"

GitLab 裡,

Protected branch(受保護分支) 和 Protected tag(受保護標籤)
是用來防止重要分支或標籤被隨意修改、刪除、或由沒有權限的人 push 的安全機制。


Protected branch(受保護分支) 和 Protected tag (受保護標籤)

1. Protected branch(受保護分支)

主要特點:

範例情境


2. Protected tag(受保護標籤)

主要特點:

範例情境


3. 為什麼與 CI/CD Variables 有關

當你在 GitLab CI/CD 中將變數設定為 Protected = ✅ 時:

舉例

deploy:
  stage: deploy
  script:
    - echo $PROD_API_KEY

這是 Protected Branch / Tag 與 CI/CD 變數注入邏輯對照表

Pipeline 觸發來源 變數 Protected 設定 變數是否注入 說明
Protected branch(例如 master ✅ Protected ✅ 注入 變數只對受保護分支生效,符合條件可使用
非 Protected branch(例如 feature/test ✅ Protected ❌ 不注入 變數不會被注入,避免敏感資料外洩
Protected tag(例如 v1.0.0 ✅ Protected ✅ 注入 變數會注入到受保護標籤的 Pipeline
非 Protected tag(例如 test-1 ✅ Protected ❌ 不注入 變數不會被注入
任意 branch/tag ❌ 未 Protected ✅ 注入 不受限制,所有 Pipeline 都能用變數

💡 建議用法


✅ Pipeline triggers

image-1755166426157.png

你這張圖是 GitLab Pipeline Trigger 設定頁面,它的用途是建立一組 Trigger Token,讓外部系統或腳本可以直接觸發專案的 CI/CD Pipeline,而不用透過 Git push 或 Merge Request。


1. Trigger Token


2. 觸發方式

(1) 用 cURL

curl -X POST --fail \
  -F token=YOUR_TOKEN \
  -F ref=分支或tag名稱 \
  http://10.10.10.10/api/v4/projects/2406/trigger/pipeline

(2) 在 .gitlab-ci.yml 裡呼叫

script:
  - "curl -X POST --fail -F token=YOUR_TOKEN -F ref=master http://10.10.10.10/api/v4/projects/2406/trigger/pipeline"

(3) 用 Webhook 直接 GET

http://10.10.10.10/api/v4/projects/2406/ref/master/trigger/pipeline?token=YOUR_TOKEN

3. 傳入 Pipeline 變數

可以讓外部觸發時同時傳遞變數:

curl -X POST --fail \
  -F token=YOUR_TOKEN \
  -F ref=master \
  -F "variables[RUN_NIGHTLY_BUILD]=true" \
  http://10.10.10.10/api/v4/projects/2406/trigger/pipeline

4. 使用場景


💡 建議:


✅ Deploy freezes(部署凍結)

image-1755166820184.png

你這張圖是 GitLab 的 Deploy freezes(部署凍結)設定頁面,用來在特定時間區間禁止部署,避免在敏感時段(例如假日、系統維護時間、尖峰時段)誤發佈程式。


圖中設定解讀


功能運作方式

  1. 這裡的時間範圍只是定義凍結時段

  2. 要生效,必須在 .gitlab-ci.yml 的部署 job 中加上:

    deploy_job:
      stage: deploy
      script:
        - echo "Deploying..."
      rules:
        - if: $CI_DEPLOY_FREEZE == "true"
          when: never
        - when: on_success
    

    或使用 GitLab 內建的 deploy_freeze 規則

  3. 凍結期間,對應的部署 job 會直接跳過,不會觸發。


使用場景


✅ Token Access

image-1755167118948.png

這是 GitLab 專案設定裡的 Token Access(CI_JOB_TOKEN 存取控制) 功能,主要用來限制 CI/CD 任務中 CI_JOB_TOKEN 變數可以存取的其他專案,避免被濫用。



用途

  1. 跨專案存取 API
    在 CI/CD pipeline 中,可能需要用 curlwget 呼叫其他 GitLab 專案的 API,例如下載 artifact、觸發 pipeline。

  2. 限制安全風險
    如果沒有啟用限制,惡意程式碼可以利用 CI_JOB_TOKEN 存取同一 GitLab instance 中所有公開或有權限的專案

  3. 最佳實務

    • 如果專案需要 CI_JOB_TOKEN 存取別的專案 → 開啟並只加允許的專案。

    • 如果專案不需要跨專案存取 → 建議直接開啟限制並不加任何專案。


範例:跨專案下載 Artifact

假設專案 A 的 pipeline 要下載專案 B 的最新 build:

script:
  - curl --header "JOB-TOKEN: $CI_JOB_TOKEN" \
         "https://gitlab.example.com/api/v4/projects/123/jobs/artifacts/main/download?job=build" \
         -o artifact.zip

如果你啟用了限制,就必須在專案 B 裡把專案 A 加進「Projects that can be accessed」清單,否則會 403 Forbidden


 

 

【GitLab】使用ssh clone 專案

以下是在 GitLab 使用 SSH 方式 clone 專案的完整步驟,假設你的 GitLab 伺服器是公司內部或自架的,也適用:


1️⃣ 產生並設定 SSH Key

  1. 建立 SSH Key

    ssh-keygen 
    
    • 出現檔案路徑提示時直接按 Enter (預設~/.ssh/id_rsa.pub)

    • 登入 GitLab → 右上角 使用者頭像PreferencesSSH Keys

    • 貼上 ~/.ssh/id_rsa.pub 內容。


2️⃣ 測試連線

確認 GitLab 可透過 SSH 連線:

ssh -T git@your.gitlab.host

3️⃣ 取得專案的 SSH URL

在 GitLab 專案頁面:


4️⃣ 執行 Clone

git clone git@gitlab.example.com:group-name/project-name.git

5️⃣ 常見問題排查

問題 檢查方式
Permission denied (publickey) 確認 ssh-agent 有加入金鑰:ssh-add -l
找不到 Host 檢查網路、防火牆,或在 ~/.ssh/config 加入 Host 設定
公司內網 GitLab 需確保內部 DNS 或 VPN 正確

範例 .ssh/config(可簡化命令)

Host gitlab-company
    HostName gitlab.example.com
    User git
    IdentityFile ~/.ssh/id_ed25519

然後可用:

git clone git@gitlab-company:group-name/project-name.git

以上步驟完成後,你就能用 SSH 方式安全地 git clone GitLab 專案並進行後續開發。