Skip to main content

Concept and usage

The kubeconfig file configures access to Kubernetes clusters by specifying cluster, user, and context information. Without it, you must supply authentication details on every kubectl command:
kubectl get pods \
  --server=https://<cluster-ip>:<port> \
  --client-certificate=<path-to-client-certificate> \
  --client-key=<path-to-client-key> \
  --certificate-authority=<path-to-ca-certificate>
The kubeconfig file avoids this repetition by storing the configuration.

Methods

Viewing and switching contexts

kubectl config -h
kubectl config view                           # view current kubeconfig
kubectl config view --kubeconfig=config       # view a specific kubeconfig file

kubectl config use-context <context-name>     # switch active context
kubectl config use-context prod@production
To set the default context in the file:
config
apiVersion: v1
kind: Config
current-context: prod@production
...

Setting a default kubeconfig file

export KUBECONFIG=<file-path>
export KUBECONFIG=/new-kube-config

# Or persist it in .bashrc
echo "export KUBECONFIG=/root/my-kube-config" >> ~/.bashrc
source ~/.bashrc

Using base64-encoded certificate data

Instead of pointing to a certificate file with certificate-authority, you can embed the certificate data directly as base64:
config
apiVersion: v1
kind: Config
clusters:
  - name: production
    cluster:
      server: https://production:6443
      certificate-authority-data: <base64-encoded-ca-certificate>
# Encode the CA certificate to base64
cat /etc/kubernetes/pki/ca.crt | base64 -w 0

# Decode base64-encoded data
echo "<base64-encoded-ca-certificate>" | base64 -d

Build docs developers (and LLMs) love