Mosquitto: 6. GitLab CI

本文件是在 CI/CD 流水线中集成 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 实例。

您可以将以下配置保存为 .gitlab-ci.yml。每次流水线运行都会为测试启动一个全新的真实 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,该部分即使作业失败也会执行,因此您的 Mosquitto 服务会被及时移除,避免产生不必要的费用。

在 GitLab 中,after_script 会在 全新 shell 中运行。为此,脚本在添加服务后立即将服务 ID 写入 service.env,删除前再重新加载。这样即使作业中途失败,也能确保服务被删除。