Kubernets ServiceAccount로 kuebconfig 파일 생성하기

최대 1 분 소요

서비스계정(ServiceAccount) 생성

kubectl create serviceaccount super-man

ClusterRole 또는 Role Binding

kubectlcreate clusterrolebinding cluster-admin:super-man --clusterrole=cluster-admin --serviceaccount=default:super-man

Kubernets ServiceAccount로 kuebconfig 파일 생성하기

# your server name goes here
server=https://localhost:6443
# the name of the service account
name=SERVICE_ACCOUNT_NAME
# the name of the namespace
namespace=default

token_name=$(kubectl -n $namespace get serviceaccount $name -o jsonpath='{.secrets[].name}')
ca=$(kubectl -n $namespace get secret/$token_name -o jsonpath='{.data.ca\.crt}')
token=$(kubectl -n $namespace get secret/$token_name -o jsonpath='{.data.token}' | base64 --decode)
namespace=$(kubectl -n $namespace get secret/$token_name -o jsonpath='{.data.namespace}' | base64 --decode)

echo "
apiVersion: v1
kind: Config
clusters:
- name: default-cluster
  cluster:
    certificate-authority-data: ${ca}
    server: ${server}
contexts:
- name: default-context
  context:
    cluster: default-cluster
    namespace: ${namespace}
    user: ${name}
current-context: default-context
users:
- name: ${name}
  user:
    token: ${token}
" > kubeconfig