Mosquitto: 2. 服務生命週期腳本

此文件屬於GitHub Actions 及 GitLab CI指南的一部分。請在此處查看完整指南:直接於您的 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 實例。

以下是一個完整的腳本範例,涵蓋服務的全生命週期。您會看到只需幾個指令即可完成設定。您可於下方各平台區段複製對應的 YAML 範本。

#!/bin/bash
set -euo pipefail

# STACKHERO_TOKEN 由 CI 機密提供,CLI 會自動讀取。

stackName="ci-mosquitto-$$"          # 每次執行唯一的 stack 名稱
serviceStore="mosquitto"             # Mosquitto 服務 store
instance="200"        # 如有需要可調整(見步驟 3)
region="europe"                         # 區域名稱(可用 stackhero regions-list 查詢)

# 1. 安裝 CLI 至 runner
curl -fsSL https://www.stackhero.io/install.sh | sh

# 2. 安裝 smoke test 所需 client(jq + curl 為基本需求)
apt-get update && apt-get install -y --no-install-recommends jq curl mosquitto-clients

# 3. 建立本次執行專屬的 stack
stackId=$(stackhero --format=script stack-create --name="$stackName")
echo "Stack created: $stackId"

# 4. 加入 Mosquitto 並取得其 service id
serviceId=$(stackhero --format=script service-add \
  --stack="$stackId" \
  --service-store="$serviceStore" \
  --instance="$instance" \
  --region="$region")
echo "Service added: $serviceId"

# 5. 等待服務啟動(可能需數分鐘)
stackhero service-wait-for --service="$serviceId"

# 6. 讀取設定(包含產生的認證資料)
config=$(stackhero service-configuration-get --service="$serviceId" --format=json)

# 7. 擷取所需認證資料
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')

# 8. Smoke test: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 存取。"

清理步驟(刪除服務、等待刪除完成、再刪除 stack)會在下方各平台專屬區段說明。這樣可確保即使 smoke test 失敗也會自動清理。

Stack 必須為空才能刪除。請務必先刪除服務並等待其移除,再刪除 stack。service-wait-for 指令可確保服務已啟動或已刪除,是等待刪除的最佳工具。