Elasticsearch: 5. GitHub Actions

本文件是在 CI/CD 中自動啟用與測試 Elasticsearch 服務指南的一部分。請在此處查看完整指南:透過 GitHub Actions 或 GitLab CI pipeline 啟動真實的 Elasticsearch 服務,執行測試並自動銷毀。

👋 歡迎使用 Stackhero 文件

Stackhero 提供專為專業人士設計的全託管 Elasticsearch cloud 服務,適合需要大規模可靠搜尋、分析與日誌記錄的您。

  • 穩定的效能與強化的安全性,採用專屬私有基礎架構。
  • 輕鬆設定受 HTTPS 保護的自訂網域名稱。

快速開始,專注於您的業務:您只需約 5 分鐘即可擁有可用於生產環境的 Elasticsearch cloud hosting 環境,日常維護與安全性皆由我們為您處理。

請將下列內容儲存為 .github/workflows/ci.yml。之後每次 push 或 pull request 都會針對真實的 Elasticsearch 實例執行測試。

name: CI with Elasticsearch

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    env:
      STACKHERO_TOKEN: ${{ secrets.STACKHERO_TOKEN }}
      STACK: CI                            # 步驟 2 建立的 stack
      INSTANCE: "20G"   # 可依需求調整(見步驟 4)
      REGION: europe
    steps:
      - uses: actions/checkout@v4

      - name: 安裝 client 與 Stackhero CLI
        run: |
          sudo sh -c "apt-get update && apt-get install -y --no-install-recommends ca-certificates jq curl"
          curl -fsSL https://www.stackhero.io/install.sh | STACKHERO_INSTALL_DIR="$HOME/.local/bin" sh
          echo "$HOME/.local/bin" >> "$GITHUB_PATH"

      - name: 新增 Elasticsearch 服務
        run: |
          set -euo pipefail
          SERVICE_ID=$(stackhero --format=script service-add \
            --stack="$STACK" \
            --service-store="elasticsearch" \
            --instance="$INSTANCE" \
            --region="$REGION")
          echo "SERVICE_ID=$SERVICE_ID" >> "$GITHUB_ENV"

      - name: 等待 Elasticsearch 啟動
        run: timeout 15m stackhero service-wait-for --service="$SERVICE_ID"

      - name: 執行測試
        run: |
          set -euo pipefail
          config=$(stackhero service-configuration-get --service="$SERVICE_ID" --format=json)
          host=$(echo "$config" | jq -r '.configuration.domain')
          user=$(echo "$config" | jq -r '.configuration.credentials.login')
          password=$(echo "$config" | jq -r '.configuration.credentials.password')
          # Call the cluster health endpoint.
          curl -fsS -u "$user:$password" "https://$host:9200/_cluster/health" | grep -q '"status"'
          echo "✅ Elasticsearch 已可從 CI 存取。"
          # 您也可以在此使用上述認證資訊執行自訂測試 ...

      - name: 刪除服務(無論成功或失敗都執行)
        if: always()
        run: |
          if [ -n "${SERVICE_ID:-}" ]; then
            stackhero service-delete --service="$SERVICE_ID" --confirm
          fi

刪除步驟設定為 if: always(),因此無論測試失敗或手動取消,皆會執行。新增服務與等待啟動分為兩步,確保即使等待失敗也能正確取得服務 ID。