RabbitMQ: 3. 服務生命週期腳本
本文件是在 CI/CD 中自動啟用與測試 RabbitMQ 服務指南的一部分。請在此處查看完整指南:透過 GitHub Actions 或 GitLab CI pipeline 啟動真實的 RabbitMQ 服務,執行測試並自動銷毀。
以下是一個完整的腳本範例,涵蓋服務的全生命週期。只需幾個指令即可完成設定。您也可以直接複製下方各平台的 YAML 範例。
#!/bin/bash
set -euo pipefail
# STACKHERO_TOKEN 由 CI 機密提供,CLI 會自動讀取。
stack="CI" # 步驟 2 建立的 stack 名稱
serviceStore="rabbitmq" # RabbitMQ 服務 store
instance="200" # 可依需求調整(見步驟 4)
region="europe" # 區域名稱(可用 stackhero regions-list 查詢)
# 1. 安裝 smoke test 會用到的 client(需 root 權限,或加 sudo)
apt-get update && apt-get install -y --no-install-recommends ca-certificates jq curl
# 2. 在 runner 上安裝 CLI
curl -fsSL https://www.stackhero.io/install.sh | STACKHERO_INSTALL_DIR="$HOME/.local/bin" sh
export PATH="$HOME/.local/bin:$PATH"
# 3. 將 RabbitMQ 加入 CI stack 並取得服務 ID
serviceId=$(stackhero --format=script service-add \
--stack="$stack" \
--service-store="$serviceStore" \
--instance="$instance" \
--region="$region")
echo "Service added: $serviceId"
# 4. 無論腳本成功或失敗,結束時都刪除服務
trap 'stackhero service-delete --service="$serviceId" --confirm' EXIT
# 5. 等待服務啟動(通常需數分鐘)
timeout 15m stackhero service-wait-for --service="$serviceId"
# 6. 讀取服務設定(包含產生的認證資訊)
config=$(stackhero service-configuration-get --service="$serviceId" --format=json)
# 7. 取得所需認證資訊
host=$(echo "$config" | jq -r '.configuration.domain')
password=$(echo "$config" | jq -r '.configuration.password')
# 8. 執行 smoke test:Call the management API (health check, falling back to overview).
curl -fsS -u "admin:$password" "https://$host/api/health/checks/alarms" | grep -q '"status":"ok"' || curl -fsS -u "admin:$password" "https://$host/api/overview" | grep -q '"rabbitmq_version"'
echo "✅ RabbitMQ 已可從 CI 存取。"
唯一需要清理的是服務本身:stack 會保留供下次使用。下方 YAML 範例中,刪除服務是獨立步驟,CI 會在任何情況下執行(即使測試失敗),確保您不會因閒置服務而產生費用。
timeout 15m 會限制等待時間。若服務未能啟動,流程會在幾分鐘內失敗並自動刪除服務,而不會等到 CI 的最大時限。