Elasticsearch: 3. 生命周期脚本

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

👋 欢迎来到 Stackhero 文档中心

Stackhero 提供面向专业人士的全托管 Elasticsearch cloud 服务,适用于需要大规模可靠搜索、分析和日志的场景。

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

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

以下是一个完整的服务生命周期管理脚本示例,展示了整个流程的简洁性,仅需几条命令即可完成。您可以在下方根据平台直接复制对应的 YAML 配置。

#!/bin/bash
set -euo pipefail

# STACKHERO_TOKEN 由 CI 密钥提供,CLI 会自动读取。

stack="CI"                              # 第 2 步创建的 stack
serviceStore="elasticsearch"             # Elasticsearch 服务商店
instance="20G"        # 如有需要可修改(见第 4 步)
region="europe"                         # 区域名称(可通过 stackhero regions-list 查看)

# 1. 安装 smoke test 所需的客户端(需 root 权限,或加 sudo)
apt-get update && apt-get install -y --no-install-recommends ca-certificates jq curl

# 2. 在 runner 上安装 CLI
curl -fsSL https://www.stackhero.io/install.sh | STACKHERO_INSTALL_DIR="$HOME/.local/bin" sh
export PATH="$HOME/.local/bin:$PATH"

# 3. 将 Elasticsearch 添加到 CI stack 并获取服务 ID
serviceId=$(stackhero --format=script service-add \
  --stack="$stack" \
  --service-store="$serviceStore" \
  --instance="$instance" \
  --region="$region")
echo "Service added: $serviceId"

# 4. 脚本结束时无论成功或失败都删除服务
trap 'stackhero service-delete --service="$serviceId" --confirm' EXIT

# 5. 等待服务启动(通常需几分钟)
timeout 15m 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.credentials.login')
password=$(echo "$config" | jq -r '.configuration.credentials.password')

# 8. Smoke test: Call the cluster health endpoint.
curl -fsS -u "$user:$password" "https://$host:9200/_cluster/health" | grep -q '"status"'

echo "✅ Elasticsearch 已可从 CI 访问。"

唯一的清理操作就是删除服务:stack 会保留用于下次运行。在下方 YAML 示例中,删除操作作为独立步骤,无论测试是否失败,CI 都会执行该步骤,确保不会因未使用的服务产生费用。

timeout 15m 用于限制等待时间。如果服务未能启动,流水线会在几分钟内失败并自动删除服务,而不会一直等到 CI 的超时时间。