쿠버네티스

동적 Kubeconfig 생성 (Dynamic Kubeconfig Generation)

ipxy 2025. 3. 23. 08:11
728x90

목표:

  • 고정된 Kubeconfig 없이 필요할 때만 생성하여 보안성 유지
  • 각 클러스터에서 자동으로 Kubeconfig 생성
  • 사용 후 일정 시간 뒤 자동 만료되도록 설정
  • Vault, Cluster API, 또는 Kubeconfig 요청 API를 활용하여 자동화

🚀 1. 왜 동적 Kubeconfig 생성이 필요한가?

기존 방식(Kubeconfig 파일 직접 저장)은 다음과 같은 문제점이 있음
🔴 보안 취약: 모든 클러스터의 Kubeconfig를 미리 저장하면 노출 위험이 있음
🔴 관리 부담: 5000개 이상의 클러스터가 있을 경우, Kubeconfig를 개별 관리하기 어려움
🔴 사용하지 않는 Kubeconfig 노출: 사용하지 않더라도 파일이 유지되면 해킹 가능성 증가

해결 방법: "필요할 때만 동적으로 Kubeconfig를 생성 & 사용 후 삭제"


📌 2. 동적 Kubeconfig 생성 방법

방법  설명 장점 단점
ServiceAccount Token 방식 K3s에서 ServiceAccount Token을 동적으로 생성 높은 보안성, 필요할 때만 생성 추가 API 필요
Vault + Kubeconfig 동적 요청 HashiCorp Vault에서 Kubeconfig 발급 중앙 집중화, 보안성 높음 Vault 운영 필요
Cluster API 사용 Cluster API에서 Kubeconfig 자동 생성 완전 자동화 가능 초기 설정 필요
Kubeconfig API Gateway API를 통해 Kubeconfig 요청 시 생성 사용 편리, 클러스터 수 무제한 관리 가능 API 개발 필요

대규모(5000개 이상) K3s 클러스터를 관리할 경우, API 기반 동적 Kubeconfig 생성이 최적!


📌 3. 방법 1: ServiceAccount 기반 동적 Kubeconfig 생성

각 K8s 클러스터에서 Kubeconfig를 미리 저장하지 않고,
필요할 때 ServiceAccount의 Token을 발급하여 동적으로 Kubeconfig를 생성하는 방법입니다.

(1) K8s 클러스터에서 ServiceAccount 생성

apiVersion: v1
kind: ServiceAccount
metadata:
  name: dynamic-kubeconfig
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: dynamic-kubeconfig-role
rules:
  - apiGroups: [""]
    resources: ["pods", "nodes", "services", "configmaps", "secrets"]
    verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: dynamic-kubeconfig-binding
subjects:
  - kind: ServiceAccount
    name: dynamic-kubeconfig
    namespace: kube-system
roleRef:
  kind: ClusterRole
  name: dynamic-kubeconfig-role
  apiGroup: rbac.authorization.k8s.io

이제 dynamic-kubeconfig ServiceAccount가 최소한의 권한으로 Kubeconfig를 생성 가능!


(2) Kubeconfig 동적 생성 스크립트

각 K8s 클러스터에서 사용자가 요청하면 ServiceAccount Token을 발급하여 Kubeconfig를 동적으로 생성합니다.

📌 자동 Kubeconfig 생성 스크립트

#!/bin/bash

# K8s 클러스터 정보 가져오기
CLUSTER_NAME="k8s-cluster-123"
SERVER="https://$(kubectl cluster-info | grep 'Kubernetes control plane' | awk '{print $NF}')"

# ServiceAccount Token 동적 생성
TOKEN=$(kubectl create token dynamic-kubeconfig -n kube-system --duration=30m)

# Kubeconfig 파일 생성
cat <<EOF > /tmp/kubeconfig-${CLUSTER_NAME}.yaml
apiVersion: v1
kind: Config
clusters:
- cluster:
    server: ${SERVER}
    insecure-skip-tls-verify: true
  name: ${CLUSTER_NAME}
contexts:
- context:
    cluster: ${CLUSTER_NAME}
    user: ${CLUSTER_NAME}-user
  name: ${CLUSTER_NAME}-context
current-context: ${CLUSTER_NAME}-context
users:
- name: ${CLUSTER_NAME}-user
  user:
    token: ${TOKEN}
EOF

echo "✅ Kubeconfig 생성 완료: /tmp/kubeconfig-${CLUSTER_NAME}.yaml"

📌 이 스크립트를 실행하면, 30분 동안만 유효한 Kubeconfig가 생성됨!

이제 Kubeconfig가 자동으로 생성 & 일정 시간 후 만료됨!


📌 4. 방법 2: Vault를 이용한 동적 Kubeconfig 발급

📌 HashiCorp Vault를 활용하면 Kubeconfig를 안전하게 발급 가능
(Kubeconfig를 Git 등에 저장할 필요 없음, 요청할 때만 발급됨)

(1) Vault에 Kubeconfig 저장

vault kv put secret/k3s/kubeconfig file=@/tmp/kubeconfig-k8s-cluster-123.yaml

(2) 요청 시 Kubeconfig 발급

vault kv get -field=file secret/k8s/kubeconfig > /tmp/kubeconfig.yaml
export KUBECONFIG=/tmp/kubeconfig.yaml
kubectl get nodes

Vault에서 필요할 때만 안전하게 Kubeconfig 가져오기!


📌 5. 방법 3: Cluster API 기반 동적 Kubeconfig 생성

📌 Cluster API를 사용하면 클러스터를 자동 생성하고 Kubeconfig를 제공할 수 있음

(1) Cluster API를 이용하여 클러스터 생성

apiVersion: cluster.x-k8s.io/v1beta1
kind: Cluster
metadata:
  name: k8s-cluster-123
spec:
  infrastructureRef:
    apiVersion: infrastructure.cluster.x-k8s.io/v1beta1
    kind: K8sCluster
    name: k8s-cluster-123

(2) Cluster API를 통해 Kubeconfig 다운로드

clusterctl get kubeconfig k8s-cluster-123 > /tmp/kubeconfig.yaml
export KUBECONFIG=/tmp/kubeconfig.yaml
kubectl get nodes

Cluster API를 활용하면 Kubeconfig가 동적으로 생성됨!


📌 6. 방법 4: Kubeconfig 요청 API 구축 (API Gateway)

📌 REST API를 사용하여 Kubeconfig를 요청하면 동적으로 발급하는 방식

(1) API Server 구축 (Python FastAPI)

from fastapi import FastAPI
import subprocess

app = FastAPI()

@app.get("/kubeconfig/{cluster_name}")
def get_kubeconfig(cluster_name: str):
    cmd = f"kubectl create token dynamic-kubeconfig -n kube-system --duration=30m"
    token = subprocess.check_output(cmd, shell=True).decode().strip()
    
    kubeconfig = f"""
apiVersion: v1
kind: Config
clusters:
- cluster:
    server: https://k8s-cluster-{cluster_name}.example.com
    insecure-skip-tls-verify: true
  name: {cluster_name}
contexts:
- context:
    cluster: {cluster_name}
    user: {cluster_name}-user
  name: {cluster_name}-context
current-context: {cluster_name}-context
users:
- name: {cluster_name}-user
  user:
    token: {token}
"""
    return {"kubeconfig": kubeconfig}

이제 http://API_SERVER/kubeconfig/k8s-cluster-123 요청 시 Kubeconfig를 자동으로 발급 가능!


📌 7. 최적의 동적 Kubeconfig 생성 방법 정리

방법 설명 장점 단점

ServiceAccount Token 방식 kubectl create token으로 Kubeconfig 발급 간단하고 빠름 K8s 버전 제한
Vault 사용 Kubeconfig를 요청할 때만 발급 보안 강화 Vault 필요
Cluster API 사용 클러스터 자동 생성 & Kubeconfig 제공 완전 자동화 초기 설정 필요
API Gateway Kubeconfig를 REST API로 제공 유연한 사용 가능 API 개발 필요

🚀 5000개 이상의 K3s 클러스터를 관리하려면?API 기반 Kubeconfig 요청 + Vault를 이용한 동적 발급 방식이 가장 적절! 

728x90