Elasticsearch: 4. GitHub Actions
本文档属于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
env:
STACKHERO_TOKEN: ${{ secrets.STACKHERO_TOKEN }}
STACK_NAME: ci-elasticsearch-${{ github.run_id }}-${{ github.run_attempt }}
INSTANCE: "20G" # 如有需要可修改(见第 3 步)
REGION: europe
steps:
- uses: actions/checkout@v4
- name: 安装 Stackhero CLI 及客户端
run: |
curl -fsSL https://www.stackhero.io/install.sh | sh
apt-get update && apt-get install -y --no-install-recommends jq curl
- name: 创建 Elasticsearch 服务
run: |
set -euo pipefail
STACK_ID=$(stackhero --format=script stack-create --name="$STACK_NAME")
echo "STACK_ID=$STACK_ID" >> "$GITHUB_ENV"
SERVICE_ID=$(stackhero --format=script service-add \
--stack="$STACK_ID" \
--service-store="elasticsearch" \
--instance="$INSTANCE" \
--region="$REGION")
echo "SERVICE_ID=$SERVICE_ID" >> "$GITHUB_ENV"
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
stackhero service-wait-for --service="$SERVICE_ID"
fi
if [ -n "${STACK_ID:-}" ]; then
stackhero stack-delete --stack="$STACK_ID" --confirm
fi
清理步骤配置了 if: always(),确保无论结果如何都会执行,保证您的 Elasticsearch 实例被删除,避免因未使用资源而产生费用。