Mosquitto: 6. GitLab CI

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

👋 歡迎來到 Stackhero 文件中心!

Stackhero 為您提供一個全代管的 Mosquitto MQTT cloud 環境,專為高可靠性與彈性設計:

  • 無限制的訊息吞吐量與資料傳輸,確保您的工作流程不會受到人為限制。
  • 透過您自有的外部 API,實現無限制的裝置驗證,讓裝置註冊與存取管理變得輕鬆無縫。
  • 進階 ACLs,可對主題(topics)、使用者及操作進行細緻權限控管。
  • 提供自訂網域名稱並內建HTTPS,打造安全且具品牌識別的端點(例如:https://mqtt.your-company.com)。
  • 零負擔更新:只需一鍵即可套用功能改進或安全修補。
  • 穩定的效能與強化的安全性,每個實例皆運行於專屬的私有基礎架構。

加速您的 IoT 專案,同時降低營運負擔。您只需幾分鐘,即可擁有一個安全、可用於生產環境的 Mosquitto MQTT cloud hosting 實例。

請將下列內容儲存為 .gitlab-ci.yml。每次 pipeline 執行時都會建立一個全新的 Mosquitto 實例供測試使用。

test:
  image: ubuntu:24.04
  timeout: 30m
  variables:
    STACK: "CI"                           # 步驟 2 建立的 stack
    INSTANCE: "200"   # 可依需求調整(見步驟 4)
    REGION: "europe"
    SERVICE_STORE: "mosquitto"
  # STACKHERO_TOKEN 來自您於步驟 1 建立的 CI/CD 變數。
  script:
    - set -euo pipefail
    - apt-get update && apt-get install -y --no-install-recommends ca-certificates jq curl mosquitto-clients
    - 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')
    - user=$(echo "$config" | jq -r '.configuration.authenticationUsers[0].login')
    - password=$(echo "$config" | jq -r '.configuration.authenticationUsers[0].password')
    # Publish a test message to a topic.
    - mosquitto_pub -h "$host" -p 8883 -u "$user" -P "$password" --capath /etc/ssl/certs -t "stackhero/ci" -m "hello"
    - echo "✅ Mosquitto 已可從 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 失敗時也會執行,確保您的 Mosquitto 服務被移除,不會產生不必要的費用。

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