Elasticsearch: 6. GitLab CI

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

👋 欢迎查阅 Stackhero 文档

Stackhero 提供面向专业人士的全托管 Elasticsearch cloud 服务,满足大规模可靠搜索、分析和日志需求。

  • 借助专属私有基础设施,实现持续高性能与强大安全性。
  • 轻松配置受 HTTPS 保护的自定义域名。

快速上手,专注于您的核心业务:您只需约 5 分钟即可拥有可用于生产环境的 Elasticsearch cloud hosting 环境,日常运维与安全由我们为您管理。

您可以将以下配置保存为 .gitlab-ci.yml。这样,每次流水线运行都会为测试启动一个全新的真实 Elasticsearch 实例。

test:
  image: ubuntu:24.04
  timeout: 30m
  variables:
    STACK: "CI"                           # 第 2 步创建的 stack
    INSTANCE: "20G"   # 如有需要可修改(见第 4 步)
    REGION: "europe"
    SERVICE_STORE: "elasticsearch"
  # STACKHERO_TOKEN 来源于第 1 步创建的 CI/CD 变量。
  script:
    - set -euo pipefail
    - apt-get update && apt-get install -y --no-install-recommends ca-certificates jq curl
    - 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.credentials.login')
    - password=$(echo "$config" | jq -r '.configuration.credentials.password')
    # Call the cluster health endpoint.
    - curl -fsS -u "$user:$password" "https://$host:9200/_cluster/health" | grep -q '"status"'
    - echo "✅ Elasticsearch 已可从 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 中。该部分即使在作业失败时也会执行,因此您的 Elasticsearch 服务会被及时删除,避免为未使用的服务付费。

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