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.
saname=veducate-sa kubectl apply -f << EOF - apiVersion: v1 kind: ServiceAccount metadata: name: ${saname} namespace: kube-system annotations: createdBy: "veducate for testing" --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: ${saname}-ca annotations: createdBy: "veducate for testing" roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - kind: ServiceAccount name: ${saname} namespace: kube-system EOF
Regards