PostgreSQL: 6. GitLab CI

此文件屬於在 CI/CD 管道中自動化部署及測試 Stackhero 服務指南的一部分。請在此處查看完整指南:透過 GitHub Actions 或 GitLab CI pipeline 快速啟動真實的 PostgreSQL 服務,執行測試並自動清理。

👋 歡迎瀏覽 Stackhero 文件!

Stackhero 為您提供全託管的 PostgreSQL cloud 服務,專為高可靠性及高速效能而設:

  • 無限連線及數據傳輸,輕鬆擴展無障礙。
  • 內建 PgAdmin 網頁介面,方便直觀管理資料庫。
  • 常用 擴充功能已預載,包括 PostGIS、TimescaleDB 及 PgVector。
  • 一鍵式 更新,確保資料庫安全及保持最新狀態。
  • 專屬私有基礎設施,提供高 效能及強大 安全性。

您只需幾分鐘即可開始使用 Stackhero 的 PostgreSQL cloud hosting。享受可靠的資料庫體驗,節省寶貴的數據管理時間。

請將下列設定儲存為 .gitlab-ci.yml。每次 pipeline 執行時,皆會為您的測試啟動全新的 PostgreSQL 實例。

test:
  image: ubuntu:24.04
  timeout: 30m
  variables:
    STACK: "CI"                           # 步驟 2 建立的 stack
    INSTANCE: "10G"   # 如有需要可調整(見步驟 4)
    REGION: "europe"
    SERVICE_STORE: "postgresql"
  # STACKHERO_TOKEN 來自您於步驟 1 建立的 CI/CD 變數。
  script:
    - set -euo pipefail
    - apt-get update && apt-get install -y --no-install-recommends ca-certificates jq curl postgresql-client
    - curl -fsSL https://www.stackhero.io/install.sh | sh
    - SERVICE_ID=$(stackhero --format=script service-add --stack="$STACK" --service-store="$SERVICE_STORE" --instance="$INSTANCE" --region="$REGION")
    - echo "SERVICE_ID=$SERVICE_ID" > service.env
    - timeout 15m stackhero service-wait-for --service="$SERVICE_ID"
    - config=$(stackhero service-configuration-get --service="$SERVICE_ID" --format=json)
    - host=$(echo "$config" | jq -r '.configuration.domain')
    - password=$(echo "$config" | jq -r '.configuration.password')
    # Run a trivial query against the database.
    - PGPASSWORD="$password" psql "host=$host port=5432 user=admin dbname=admin sslmode=require" -c "SELECT 1;"
    - echo "✅ PostgreSQL 已可由 CI 存取。"
    # 您亦可於此處使用上述認證資訊執行自訂測試 ...
  after_script:
    - test -f service.env && . ./service.env || true
    - >
      if [ -n "${SERVICE_ID:-}" ]; then
        stackhero service-delete --service="$SERVICE_ID" --confirm
      fi

在 GitLab 中,刪除服務會於 after_script 執行。此區段即使 job 失敗也會執行,確保您的 PostgreSQL 服務會被移除,避免產生不必要的費用。

在 GitLab,after_script 會於全新 shell執行。為處理此情況,腳本會於新增服務時將服務 ID 寫入 service.env,刪除前再讀取,確保即使 job 執行中斷,服務仍能被正確刪除。