config/scripts/export-from-consul.sh

60 lines
1.7 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env bash
# 从 Consul 导出 KV 到 idwms/*.json(首次建仓 / 对账用)
# 注意:导出会含明文密码,勿直接 commit;先人工脱敏或改用占位符
# 用法: ./scripts/export-from-consul.sh [admin|common|itfxapi|trackapi ...]
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
export KUBECONFIG="${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml}"
NS="${NAMESPACE:-prod}"
IDWMS_DIR="${ROOT}/idwms"
mkdir -p "$IDWMS_DIR"
need() { command -v "$1" >/dev/null || { echo "FAIL: 需要 $1"; exit 1; }; }
need kubectl
need curl
need jq
if [[ -z "${CONSUL_HTTP_ADDR:-}" ]]; then
CIP="$(kubectl -n "$NS" get svc consul -o jsonpath='{.spec.clusterIP}')"
CONSUL_HTTP_ADDR="http://${CIP}:8500"
fi
if [[ -z "${CONSUL_HTTP_TOKEN:-}" ]]; then
raw="$(kubectl -n "$NS" get secret consul-acl -o jsonpath='{.data.CONSUL_HTTP_TOKEN}' 2>/dev/null || true)"
if [[ -n "$raw" ]]; then
CONSUL_HTTP_TOKEN="$(printf '%s' "$raw" | base64 -d)"
fi
fi
CURL_AUTH=()
if [[ -n "${CONSUL_HTTP_TOKEN:-}" ]]; then
CURL_AUTH=(-H "X-Consul-Token: ${CONSUL_HTTP_TOKEN}")
fi
if [[ $# -eq 0 ]]; then
TARGETS=(common admin itfxapi trackapi)
else
TARGETS=("$@")
fi
for name in "${TARGETS[@]}"; do
key="idwms/${name}"
out="${IDWMS_DIR}/${name}.json"
echo "==> GET ${key}"
raw="$(curl -sS "${CURL_AUTH[@]}" "${CONSUL_HTTP_ADDR}/v1/kv/${key}?raw" || true)"
if [[ -z "$raw" ]]; then
echo "WARN: ${key} 为空或不存在,跳过"
continue
fi
if ! jq empty <<<"$raw" 2>/dev/null; then
echo "FAIL: ${key} 不是 JSON"
exit 1
fi
jq . <<<"$raw" >"$out"
echo "OK → ${out}"
done
echo "导出完成。提交前请把密码改成 \${MYSQL_ROOT_PASSWORD} 等占位符。"