Mosquitto: 4. GitHub Actions
本文件是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 實例。
請將下列內容儲存為 .github/workflows/ci.yml。從此之後,每次 push 或 pull request 都會針對真實的 Mosquitto 實例執行測試。
name: 使用 Mosquitto 的 CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
env:
STACKHERO_TOKEN: ${{ secrets.STACKHERO_TOKEN }}
STACK_NAME: ci-mosquitto-${{ github.run_id }}-${{ github.run_attempt }}
INSTANCE: "200" # 如有需要可調整(見步驟 3)
REGION: europe
steps:
- uses: actions/checkout@v4
- name: 安裝 Stackhero CLI 與 client
run: |
curl -fsSL https://www.stackhero.io/install.sh | sh
apt-get update && apt-get install -y --no-install-recommends jq curl mosquitto-clients
- name: 建立 Mosquitto 服務
run: |
set -euo pipefail
STACK_ID=$(stackhero --format=script stack-create --name="$STACK_NAME")
echo "STACK_ID=$STACK_ID" >> "$GITHUB_ENV"
SERVICE_ID=$(stackhero --format=script service-add \
--stack="$STACK_ID" \
--service-store="mosquitto" \
--instance="$INSTANCE" \
--region="$REGION")
echo "SERVICE_ID=$SERVICE_ID" >> "$GITHUB_ENV"
stackhero service-wait-for --service="$SERVICE_ID"
- name: 執行 Mosquitto 測試
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.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 存取。"
# 您也可以在此使用上述認證資訊執行自訂測試 ...
- name: 清理資源(無論成功或失敗皆執行)
if: always()
run: |
if [ -n "${SERVICE_ID:-}" ]; then
stackhero service-delete --service="$SERVICE_ID" --confirm
stackhero service-wait-for --service="$SERVICE_ID"
fi
if [ -n "${STACK_ID:-}" ]; then
stackhero stack-delete --stack="$STACK_ID" --confirm
fi
清理步驟設定為 if: always(),確保無論流程結果如何都會執行,讓您的 Mosquitto 實例被刪除,避免產生不必要的資源費用。