Recently I was working with a software integration that required a Kubernetes Kubeconfig file. I didn’t want to provide my own kubeconfig file, and I also wanted to set the right permissions via a service account.
Below is the code I put together for this, partially inspired by this stackoverflow post I came across. If you scroll further, I’ve included creating a service account and giving it cluster-admin access, in case you need it.
######################
# Set the variables #
# #
######################
clusterName=veducate-eks
## the Namespace and ServiceAccount name that is used for the config
namespace=kube-system
serviceAccount=veducate-ca
## New Kubeconfig file name
newfile=something.kubeconfig
######################
# Main Script #
# #
######################
server=${kubectl config view --minify --raw -o jsonpath='{.clusters[].cluster.server}' | sed 's/"//'}
secretName=$(kubectl --namespace $namespace get serviceAccount $serviceAccount -o jsonpath='{.secrets[0].name}')
ca=$(kubectl --namespace $namespace get secret/$secretName -o jsonpath='{.data.ca\.crt}')
token=$(kubectl --namespace $namespace get secret/$secretName -o jsonpath='{.data.token}' | base64 --decode)
echo "
---
apiVersion: v1
kind: Config
clusters:
- name: ${clusterName}
cluster:
certificate-authority-data: ${ca}
server: ${server}
contexts:
- name: ${serviceAccount}@${clusterName}
context:
cluster: ${clusterName}
namespace: ${namespace}
user: ${serviceAccount}
users:
- name: ${serviceAccount}
user:
token: ${token}
current-context: ${serviceAccount}@${clusterName}
" >> ${newfile}.yaml
Below is the code I used to create a Service Account that has cluster admin access, then if I use the above code, I can get a kubeconfig file for that. Continue reading Creating a kubeconfig file for a Kubernetes Service Account

