Accessing a Kubernetes cluster with a Service Account

Accessing a Kubernetes cluster with a Service Account

Sometimes you need to access Kubernetes programmatically but the kubeconfig given by the provider uses a plugin and your program does not have access to that plugin, or other times the credentials provided in the kubeconfig have a short term expiration so you want a more durable way to connect to the cluster. On either of these cases you can setup a service account to do that. Let's go over the steps:

# Create the service account
kubectl -n kube-system create sa myapp-sa

# Bind the new service account to the clusterrole you want
kubectl create clusterrolebinding myapp-sa-cl-adm --clusterrole=cluster-admin --serviceaccount=kube-system:myapp-sa

# Get the token name
TOKEN_NAME=`kubectl -n kube-system get serviceaccount/myapp-sa -o jsonpath='{.secrets[0].name}'`

# Get token value 
TOKEN=`kubectl -n kube-system get secret $TOKEN_NAME -o jsonpath='{.data.token}'| base64 --decode`

# Add the credentials to kubeconfig 
kubectl config set-credentials myapp-sa --token=$TOKEN

# Set the user to the context
kubectl config set-context --current --user=myapp-sa

# Validate the user is working 
kubectl get pods -A        

要查看或添加评论,请登录

社区洞察