1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

管理クラスタにある すべての CAPI Cluster の kubeconfig を、手元の kubeconfig にマージする

Last updated at Posted at 2025-10-23

スクリプト

#!/usr/bin/env bash
set -euo pipefail

# 管理クラスタ上の全 Cluster API Cluster の kubeconfig を取得し、
# 現在使用中の kubeconfig に直接マージする。

need() { command -v "$1" >/dev/null 2>&1 || { echo "[error] '$1' not found"; exit 1; }; }
need kubectl
need clusterctl

# 既存 kubeconfig の決定
if [[ -n "${KUBECONFIG:-}" ]]; then
  TARGET="${KUBECONFIG%%:*}"  # 複数指定時は先頭を採用
  ORIG_ENV="$KUBECONFIG"
else
  mkdir -p "${HOME}/.kube"
  TARGET="${HOME}/.kube/config"
  ORIG_ENV="$TARGET"
fi

TMPDIR="$(mktemp -d)"
trap 'rm -rf "$TMPDIR"' EXIT
LIST="$TMPDIR/cluster-list.txt"
GENS=""

echo "[info] Listing Cluster API clusters on the management cluster..."
kubectl get clusters -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\n"}{end}' > "$LIST" || true

if [[ ! -s "$LIST" ]]; then
  echo "[warn] No Cluster API clusters found. Nothing to merge."
  exit 0
fi

# 1クラスタずつ取得 & コンテキスト名を "<ns>/<ctx>" にして衝突回避
while IFS=$'\t' read -r ns name; do
  [[ -z "${ns:-}" || -z "${name:-}" ]] && continue
  f="$TMPDIR/${ns}-${name}.kubeconfig"
  echo "[info] Fetching kubeconfig for ${ns}/${name} ..."
  clusterctl get kubeconfig "$name" --namespace "$ns" > "$f"

  for ctx in $(kubectl --kubeconfig "$f" config get-contexts -o name || true); do
    new_ctx="${ns}/${ctx}"
    if [[ "$ctx" != "$new_ctx" ]]; then
      kubectl --kubeconfig "$f" config rename-context "$ctx" "$new_ctx" >/dev/null || true
    fi
  done

  [[ -z "$GENS" ]] && GENS="$f" || GENS="$GENS:$f"
done < "$LIST"

# 既存 kubeconfig のバックアップ
ts="$(date +%Y%m%d%H%M%S)"
if [[ -f "$TARGET" ]]; then
  cp -p "$TARGET" "${TARGET}.bak-${ts}"
  echo "[info] Backup created: ${TARGET}.bak-${ts}"
else
  : > "$TARGET"
fi

# 既存 + 生成をまとめて flatten して上書き
ALL_SOURCES="${ORIG_ENV}:${GENS}"
ALL_SOURCES="${ALL_SOURCES#:}"; ALL_SOURCES="${ALL_SOURCES%:}"

echo "[info] Merging into: $TARGET"
KUBECONFIG="$ALL_SOURCES" kubectl config view --flatten > "${TARGET}.tmp"
chmod 600 "${TARGET}.tmp"
mv -f "${TARGET}.tmp" "$TARGET"

echo "[done] Merged kubeconfig written to: $TARGET"
kubectl --kubeconfig "$TARGET" config get-contexts -o name || true
chmod +x ./merge-capi-kubeconfigs.sh
./merge-capi-kubeconfigs.sh
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?