Mosquitto: 4. GitHub Actions

本文档属于GitHub Actions & GitLab CI指南的一部分。您可以在此处查看完整指南:通过您的 GitHub Actions 或 GitLab CI 流水线启动一个真实的 Mosquitto 服务,运行测试并自动销毁

👋 欢迎查阅 Stackhero 文档!

Stackhero 为您提供一个全托管的 Mosquitto MQTT cloud 环境,专为高可靠性和灵活性设计:

  • 无限制的消息吞吐量和数据传输,确保您的工作流不会受到人为限制。
  • 通过您自有的外部 API 实现无限制的设备认证,让设备接入和访问管理更加便捷。
  • 高级 ACLs,可对主题、用户和操作进行精细化权限控制。
  • 提供自定义域名,内置HTTPS,为您的终端提供安全且具备品牌形象的访问入口(例如:https://mqtt.your-company.com)。
  • 一键升级,轻松应用功能改进或安全补丁,无需繁琐操作。
  • 始终如一的高性能强安全性,每个实例均运行在专属私有基础设施上。

加速您的 IoT 项目,降低运维负担。只需几分钟,您即可拥有一个安全、可用于生产环境的 Mosquitto MQTT cloud hosting 实例。

您可以将以下内容保存为 .github/workflows/ci.yml。此后,每次 push 或 pull request 都会针对真实的 Mosquitto 实例运行测试。

name: CI with Mosquitto

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 及客户端
        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 实例被删除,避免因未使用资源而产生费用。