Skip to content

Kubeconfig

https://coreos.com/blog/kubectl-tips-and-tricks

To use a specifig config file, use --kubeconfig=<file_name> or KUBECONFIG environment variable.

Merging config files

Merging Kubernetes configurations is a common pattern if you are interacting with multiple Kubernetes clusters. When working with multiple configs you use the concept of context to describe the parameters that kubectl will use to target a specific cluster. You can use the environment variable KUBECONFIG to point at your configuration files and to merge them

Swithch to new context

$ kubectl config get-contexts
CURRENT   NAME                                    CLUSTER                                 AUTHINFO     NAMESPACE
*         aws-phc-analytics-cluster               aws-phc-analytics-cluster               user-6btk9
          rancher-management-plane-do-not-touch   rancher-management-plane-do-not-touch   user-6btk9

$ kubectl config use-context  rancher-management-plane-do-not-touch
Switched to context "rancher-management-plane-do-not-touch".


$ kubectl config get-contexts
CURRENT   NAME                                    CLUSTER                                 AUTHINFO     NAMESPACE
          aws-phc-analytics-cluster               aws-phc-analytics-cluster               user-6btk9
*         rancher-management-plane-do-not-touch   rancher-management-plane-do-not-touch   user-6btk9

Create kubeconfig using service account

kubectl create serviceaccount cluster-admin -n kube-system
kubectl create token cluster-admin -n kube-system # for kubernetes version 1.25 and above
kubectl create clusterrolebinding cluster:admin --clusterrole=cluster-admin --serviceaccount=kube-system:cluster-admin
export TOKEN_NAME=$(kubectl get sa -n kube-system cluster-admin -o jsonpath='{.secrets[0].name}')
export TOKEN=$(kubectl get secret -n kube-system $TOKEN_NAME -o jsonpath='{.data.token}'| base64 --decode)
export CURRENT_CONTEXT=$(kubectl config current-context)
export CLUSTER_NAME=$(echo ${CURRENT_CONTEXT} | awk -F/ '{print $2}')
export CLUSTER_CA=$(kubectl config view --raw -o=go-template='{{range .clusters}}{{if eq .name "'''${CURRENT_CLUSTER}'''"}}"{{with index .cluster "certificate-authority-data" }}{{.}}{{end}}"{{ end }}{{ end }}')
export CLUSTER_SERVER=$(kubectl config view --raw -o=go-template='{{range .clusters}}{{if eq .name "'''${CURRENT_CLUSTER}'''"}}{{ .cluster.server }}{{end}}{{ end }}')



cat << EOF > $CLUSTER_NAME
apiVersion: v1
clusters:
  - cluster:
      certificate-authority-data: ${CLUSTER_CA}
      server: ${CLUSTER_SERVER}
    name: ${CLUSTER_NAME}
contexts:
  - context:
      cluster: ${CLUSTER_NAME}
      user: cluster-admin
    name: ${CLUSTER_NAME}
current-context: ${CLUSTER_NAME}
kind: Config
preferences: {}
users:
  - name: cluster-admin
    user:
      token: ${TOKEN}
EOF