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. 向 CI stack 添加 Elasticsearch 并获取服务 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 的超时时间。