Elasticsearch: 5. GitHub Actions
本文件是在 CI/CD 流水线中集成 GitHub Actions 与 GitLab CI指南的一部分。您可以在这里查看完整指南:通过 GitHub Actions 或 GitLab CI 流水线启动真实的 Elasticsearch 服务,运行测试并自动销毁服务。
👋 欢迎来到 Stackhero 文档中心
Stackhero 提供面向专业人士的全托管 Elasticsearch cloud 服务,适用于需要大规模可靠搜索、分析和日志的场景。
- 通过专属私有基础设施,实现持续高性能与强大安全性。
- 轻松配置受 HTTPS 保护的自定义域名。
快速上手,专注于您的业务:您只需约 5 分钟即可拥有可用于生产环境的 Elasticsearch cloud hosting 环境,日常维护和安全由我们为您管理。
您可以将以下内容保存为 .github/workflows/ci.yml。此后,每次 push 或 pull request 都会针对真实的 Elasticsearch 实例运行测试。
name: CI with Elasticsearch
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
STACKHERO_TOKEN: ${{ secrets.STACKHERO_TOKEN }}
STACK: CI # 第 2 步创建的 stack
INSTANCE: "20G" # 如有需要可修改(见第 4 步)
REGION: europe
steps:
- uses: actions/checkout@v4
- name: 安装客户端及 Stackhero CLI
run: |
sudo sh -c "apt-get update && apt-get install -y --no-install-recommends ca-certificates jq curl"
curl -fsSL https://www.stackhero.io/install.sh | STACKHERO_INSTALL_DIR="$HOME/.local/bin" sh
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
- name: 添加 Elasticsearch 服务
run: |
set -euo pipefail
SERVICE_ID=$(stackhero --format=script service-add \
--stack="$STACK" \
--service-store="elasticsearch" \
--instance="$INSTANCE" \
--region="$REGION")
echo "SERVICE_ID=$SERVICE_ID" >> "$GITHUB_ENV"
- name: 等待 Elasticsearch 启动
run: timeout 15m stackhero service-wait-for --service="$SERVICE_ID"
- name: 针对 Elasticsearch 运行测试
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.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 访问。"
# 您也可以在此处用上方凭证运行自定义测试套件 ...
- name: 删除服务(始终执行,包括失败时)
if: always()
run: |
if [ -n "${SERVICE_ID:-}" ]; then
stackhero service-delete --service="$SERVICE_ID" --confirm
fi
删除步骤配置了 if: always(),因此无论测试失败还是手动取消,都会执行。添加服务和等待服务是分开的步骤,这样即使等待失败,服务 ID 也已保存。