2.2 Managing Kubeconfig Files, Users, & Contexts

Key Takeaways

  • A Kubeconfig file binds three fundamental structures: Clusters (API endpoints & CA data), Users (client credentials, tokens, or exec plugins), and Contexts (the binding of a User, Cluster, and default Namespace).
  • The active operational context is determined by 'current-context', inspectable via 'kubectl config current-context' and switchable via 'kubectl config use-context <name>'.
  • The '--raw' flag with 'kubectl config view' is mandatory to view embedded, unredacted certificate data ('DATA+OMITTED' is displayed otherwise).
  • Changing the default target namespace for the active context is performed imperatively via 'kubectl config set-context --current --namespace=<ns>' without altering underlying cluster or user definitions.
  • Multiple kubeconfig files are merged in memory by passing a colon-separated list to the '$KUBECONFIG' environment variable and persisted into a single file using 'kubectl config view --flatten'.
Last updated: August 2026

Managing Kubeconfig Files, Users, & Contexts

kubectl determines which Kubernetes cluster to communicate with, which credentials to authenticate with, and which default namespace to target by parsing configuration files known as kubeconfig files. By default, kubectl looks for a file located at $HOME/.kube/config.

On the CKA exam, rapid navigation between multiple clusters, switching contexts, extracting embedded TLS keys, configuring user credentials, and debugging broken connection parameters without manual YAML editing are essential speed skills.


1. Kubeconfig Anatomy & Triplet Structure

A kubeconfig file organizes cluster connectivity around three core top-level arrays and one active pointer:

  1. clusters: Defines the API server URL (server), server TLS validation (certificate-authority path or certificate-authority-data base64 string), and optional proxy URLs.
  2. users: Defines identity credentials. Can specify X.509 client certificates and private keys (client-certificate-data, client-key-data), static tokens (token), or dynamic authentication plugins (exec).
  3. contexts: A triplet binding together exactly one Cluster, one User, and an optional default Namespace.
  4. current-context: The top-level string indicating which context is actively used by kubectl commands when --context is omitted.
+-----------------------------------------------------------------------------------------+
|                                 KUBECONFIG SCHEMA BINDING                               |
|                                                                                         |
|   CLUSTERS                        CONTEXTS                           USERS              |
|   +-----------------------+       +-------------------------+       +-----------------+ |
|   | name: prod-cluster    |<------| cluster: prod-cluster   |       | name: admin-user| |
|   | server: https://...   |       | user: admin-user        |------>| cert: data...   | |
|   | ca-data: LS0tLS...    |       | namespace: default      |       | key: data...    | |
|   +-----------------------+       +-------------------------+       +-----------------+ |
|                                                ^                                        |
|   +-----------------------+                    |                    +-----------------+ |
|   | name: dev-cluster     |       +------------+------------+       | name: dev-user  | |
|   | server: https://...   |<------| name: dev-frontend      |       | token: eyJ...   | |
|   | ca-data: LS0tLS...    |       | cluster: dev-cluster    |------>+-----------------+ |
|   +-----------------------+       | user: dev-user          |                           |
|                                   | namespace: frontend     |                           |
|                                   +-------------------------+                           |
|                                                ^                                        |
|                                                |                                        |
|                                    current-context: dev-frontend                        |
+-----------------------------------------------------------------------------------------+

Complete Kubeconfig YAML Manifest Example

apiVersion: v1
kind: Config
preferences: {}
current-context: dev-frontend-context

clusters:
- name: production-cluster
  cluster:
    server: https://192.168.1.100:6443
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCg==
- name: staging-cluster
  cluster:
    server: https://192.168.1.101:6443
    certificate-authority: /etc/kubernetes/pki/ca.crt

users:
- name: alice-admin
  user:
    client-certificate-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCg==
    client-key-data: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQo=
- name: developer-token
  user:
    token: eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9...
- name: cloud-user
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1
      interactiveMode: Never
      command: aws
      args:
      - eks
      - get-token
      - --cluster-name
      - prod-eks

contexts:
- name: prod-admin-context
  context:
    cluster: production-cluster
    user: alice-admin
    namespace: default
- name: dev-frontend-context
  context:
    cluster: staging-cluster
    user: developer-token
    namespace: frontend

2. Kubeconfig Inspection with kubectl config

CommandPurposeExam Utility
kubectl config viewView current kubeconfig with certificates redactedFast overview of config structure
kubectl config view --rawView kubeconfig with full unredacted base64 certificatesExtracting embedded certs/keys
kubectl config get-contextsList all available contexts with active indicated by *Identifying current target cluster
kubectl config current-contextPrint the exact name of the active contextVerification during multi-cluster tasks
kubectl config use-context <name>Switch the active current-contextSwitching cluster/user context
kubectl config get-clustersList all defined clustersCluster inventory check
kubectl config get-usersList all defined usersUser identity inventory check

[!TIP] CKA Exam Context Switching: At the beginning of every single CKA exam question, the prompt will provide a context switch command (e.g., kubectl config use-context k8s). Always execute this command first before answering the question to avoid modifying the wrong cluster.


3. Imperative Configuration Commands (kubectl config set-*)

Avoid hand-editing YAML formatting when creating users, clusters, and contexts. Use kubectl config imperative subcommands:

1. Setting Cluster Endpoints and CAs

# Add or update a cluster entry with embedded CA
kubectl config set-cluster k8s-production \
  --server=https://10.0.0.100:6443 \
  --certificate-authority=/etc/kubernetes/pki/ca.crt \
  --embed-certs=true

2. Setting User Credentials

# Add user with client certificate and private key (embedded)
kubectl config set-credentials john-developer \
  --client-certificate=/home/john/john.crt \
  --client-key=/home/john/john.key \
  --embed-certs=true

# Add user with authentication token
kubectl config set-credentials pipeline-sa \
  --token=eyJhbGciOiJSUzI1NiIsImtpZCI6IiJ9...

3. Setting Contexts and Default Namespaces

# Create a new context linking cluster, user, and namespace
kubectl config set-context prod-frontend \
  --cluster=k8s-production \
  --user=john-developer \
  --namespace=frontend

# Change the default namespace of the CURRENT active context without modifying anything else
kubectl config set-context --current --namespace=kube-system

4. Deleting Elements

kubectl config delete-context old-context
kubectl config delete-cluster old-cluster
kubectl config delete-user old-user

4. Merging and Flattening Multiple Kubeconfigs

When managing hybrid clusters or receiving vendor-provided cluster configs, you can merge multiple files into a single unified configuration.

# Set KUBECONFIG environment variable to a colon-separated list of paths
export KUBECONFIG=~/.kube/config:/path/to/custom-cluster.kubeconfig:/path/to/backup.kubeconfig

# View merged output in memory
kubectl config get-contexts

# Flatten and persist into a single standalone file
kubectl config view --flatten > ~/.kube/merged-config

# Replace the default config with the flattened file
mv ~/.kube/merged-config ~/.kube/config
chmod 600 ~/.kube/config

5. Exec Authentication Plugins in Kubeconfig

In modern enterprise and managed cloud environments (Amazon EKS, Google GKE, Microsoft AKS), client certificates are rarely used for human developers. Instead, users entries configure dynamic exec credential plugins:

  • The exec plugin specifies an external binary (e.g., aws, gke-gcloud-auth-plugin, kubelogin) that executes locally to obtain a short-lived token.
  • The external tool outputs an ExecCredential object (client.authentication.k8s.io/v1) via stdout containing a bearer token and expiration timestamp.
  • kubectl caches the token in memory and automatically re-executes the binary when the token expires.

6. In-Cluster Pod Authentication vs Kubeconfig

Applications running inside a Pod do not require a ~/.kube/config file. Instead, the kubelet automatically mounts the in-cluster credentials at /var/run/secrets/kubernetes.io/serviceaccount/:

  • token: Projected ServiceAccount JWT
  • ca.crt: Cluster root CA
  • namespace: Current namespace string

Official client libraries (client-go, Python kubernetes SDK) automatically invoke rest.InClusterConfig() to parse these files and discover the API server via the injected environment variables KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT.


7. Troubleshooting Broken Kubeconfig Files

Common misconfigurations in kubeconfig files include:

  1. Mismatched Cluster/User Names in Context: If a context references cluster: prod but the cluster is named production-k8s, running commands fails with error: context '<name>' does not exist or cluster '<name>' is not defined.
  2. File Path References vs Embedded Data: If client-certificate points to a relative file path that is moved, commands fail. Always use --embed-certs=true to embed base64 strings.
  3. Overly Permissive File Permissions: $HOME/.kube/config contains private keys and auth tokens. Ensure permissions are set to chmod 600 ~/.kube/config.
Loading diagram...
Kubeconfig Triplet Architecture: Clusters, Users, Contexts & Pointer
Test Your Knowledge

An administrator wants all future 'kubectl' commands in the current context to target the 'database' namespace without appending '-n database' or changing the cluster/user definitions. Which command achieves this?

A
B
C
D
Test Your Knowledge

A developer needs to extract the embedded client certificate for user 'developer' from a kubeconfig file. However, running 'kubectl config view' displays 'client-certificate-data: DATA+OMITTED'. How can the developer view the unredacted base64 data?

A
B
C
D
Test Your Knowledge

You have three separate kubeconfig files: 'config-dev', 'config-stage', and 'config-prod'. What is the standard procedure to combine them into a single unified '~/.kube/config' file?

A
B
C
D