Skip to content

Module 6 — Kubeconfig & Contexts

Overview

The kubeconfig file is how kubectl knows which cluster to talk to, as which user, and in which namespace. The CKA exam frequently requires switching between clusters and contexts. This module covers the file structure, context management, and multi-cluster workflows.


1. Kubeconfig File Structure

1.1 The Three Building Blocks

A kubeconfig file has three sections that combine to form a context:

┌──────────────────────────────────────────────────────────┐
│                     kubeconfig                            │
│                                                          │
│  ┌─────────────┐   ┌─────────────┐   ┌──────────────┐   │
│  │  clusters    │   │   users     │   │  contexts    │   │
│  │             │   │             │   │              │   │
│  │ - name      │   │ - name      │   │ - cluster ───┼──▶ cluster
│  │   server    │   │   cert/token│   │   user ─────┼──▶ user
│  │   CA        │   │             │   │   namespace  │   │
│  └─────────────┘   └─────────────┘   └──────────────┘   │
│                                                          │
│  current-context: ──────────────────▶ active context     │
└──────────────────────────────────────────────────────────┘
Section What it defines
clusters API server endpoint + CA certificate
users Authentication credentials (client cert, token, etc.)
contexts A combination of cluster + user + (optional) namespace
current-context Which context is currently active

1.2 Full Example

apiVersion: v1
kind: Config
current-context: dev-context          # ← active context

clusters:
- name: dev-cluster
  cluster:
    server: https://192.168.1.10:6443
    certificate-authority-data: <base64-encoded-CA-cert>
    # OR
    # certificate-authority: /path/to/ca.crt

- name: prod-cluster
  cluster:
    server: https://10.0.0.50:6443
    certificate-authority-data: <base64-encoded-CA-cert>

users:
- name: dev-admin
  user:
    client-certificate-data: <base64-encoded-client-cert>
    client-key-data: <base64-encoded-client-key>

- name: prod-admin
  user:
    client-certificate-data: <base64-encoded-client-cert>
    client-key-data: <base64-encoded-client-key>

- name: token-user
  user:
    token: <bearer-token>

contexts:
- name: dev-context
  context:
    cluster: dev-cluster        # ← references clusters[].name
    user: dev-admin             # ← references users[].name
    namespace: development      # ← default namespace for this context

- name: prod-context
  context:
    cluster: prod-cluster
    user: prod-admin
    namespace: production

1.3 Authentication Methods in the users Section

Method Fields Common Use
Client certificate client-certificate-data + client-key-data kubeadm admin, component kubeconfigs
Bearer token token ServiceAccount tokens, OIDC
Exec-based exec.command + exec.args AWS EKS (aws eks get-token), GKE, OIDC plugins
Username/password username + password Deprecated — do not use

Exec-based example (EKS):

users:
- name: eks-user
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      command: aws
      args:
        - eks
        - get-token
        - --cluster-name
        - my-cluster

1.4 Default Location

1
2
3
4
5
6
7
8
# Default kubeconfig path
$HOME/.kube/config

# Override with environment variable
export KUBECONFIG=/path/to/custom-config

# Override per command
kubectl get pods --kubeconfig=/path/to/custom-config

1.5 Kubeconfig Files Created by kubeadm

File User Purpose
/etc/kubernetes/admin.conf kubernetes-admin Cluster admin access
/etc/kubernetes/kubelet.conf system:node:<hostname> kubelet → API server
/etc/kubernetes/scheduler.conf system:kube-scheduler Scheduler → API server
/etc/kubernetes/controller-manager.conf system:kube-controller-manager Controller manager → API server

After kubeadm init, you copy admin.conf to your user's kubeconfig:

1
2
3
mkdir -p $HOME/.kube
cp /etc/kubernetes/admin.conf $HOME/.kube/config
chown $(id -u):$(id -g) $HOME/.kube/config

2. Managing Contexts

2.1 Viewing Configuration

# View the full kubeconfig (merged from all sources)
kubectl config view

# View with secrets shown (not redacted)
kubectl config view --raw

# View only the current context
kubectl config current-context

# List all contexts
kubectl config get-contexts
# CURRENT   NAME           CLUSTER        AUTHINFO      NAMESPACE
# *         dev-context    dev-cluster    dev-admin     development
#           prod-context   prod-cluster   prod-admin    production

# List all clusters
kubectl config get-clusters

# List all users
kubectl config get-users

2.2 Switching Contexts

1
2
3
4
5
6
# Switch to a different context
kubectl config use-context prod-context

# Verify
kubectl config current-context
# prod-context

CKA Tip: The exam provides multiple clusters. Each question tells you which context to use. Always switch context at the start of each question:

kubectl config use-context <context-name>

2.3 Setting a Default Namespace for a Context

1
2
3
4
5
6
7
8
# Set the default namespace for the current context
kubectl config set-context --current --namespace=kube-system

# Set the default namespace for a specific context
kubectl config set-context dev-context --namespace=staging

# Verify
kubectl config get-contexts

This avoids typing -n <namespace> on every command.

2.4 Creating Contexts, Clusters, and Users

# Add a new cluster
kubectl config set-cluster staging-cluster \
  --server=https://192.168.2.10:6443 \
  --certificate-authority=/path/to/ca.crt

# Add a new cluster with embedded cert
kubectl config set-cluster staging-cluster \
  --server=https://192.168.2.10:6443 \
  --certificate-authority=/path/to/ca.crt \
  --embed-certs=true

# Add a new user (client certificate)
kubectl config set-credentials staging-admin \
  --client-certificate=/path/to/client.crt \
  --client-key=/path/to/client.key \
  --embed-certs=true

# Add a new user (token)
kubectl config set-credentials monitoring-sa \
  --token=<bearer-token>

# Create a new context
kubectl config set-context staging-context \
  --cluster=staging-cluster \
  --user=staging-admin \
  --namespace=default

# Switch to it
kubectl config use-context staging-context

2.5 Deleting Configuration

1
2
3
4
5
6
7
8
# Delete a context
kubectl config delete-context staging-context

# Delete a cluster
kubectl config delete-cluster staging-cluster

# Delete a user
kubectl config delete-user staging-admin

3. Working with Multiple Kubeconfig Files

3.1 Merging with KUBECONFIG Environment Variable

You can merge multiple kubeconfig files by setting the KUBECONFIG variable to a colon-separated (Linux/Mac) or semicolon-separated (Windows) list:

1
2
3
4
5
# Linux/Mac
export KUBECONFIG=$HOME/.kube/config:/path/to/cluster2-config:/path/to/cluster3-config

# Windows
set KUBECONFIG=%USERPROFILE%\.kube\config;C:\path\to\cluster2-config

kubectl merges all files in memory. Contexts, clusters, and users from all files become available:

1
2
3
4
5
# See all merged contexts
kubectl config get-contexts

# Switch between clusters from different files
kubectl config use-context cluster2-context

3.2 Merging into a Single File

1
2
3
4
5
# Merge and write to a single file
KUBECONFIG=$HOME/.kube/config:/path/to/new-config kubectl config view --flatten > /tmp/merged-config

# Replace the original
mv /tmp/merged-config $HOME/.kube/config

3.3 Per-Command Override

# Use a specific kubeconfig for one command only
kubectl get pods --kubeconfig=/path/to/other-config

3.4 Precedence Order

kubectl resolves configuration in this order:

1
2
3
1. --kubeconfig flag           (highest priority)
2. KUBECONFIG environment variable
3. $HOME/.kube/config          (default fallback)

4. Inspecting and Debugging Kubeconfig

4.1 Common Issues

Symptom Cause Fix
The connection to the server localhost:8080 was refused No kubeconfig found or KUBECONFIG not set Copy admin.conf: cp /etc/kubernetes/admin.conf ~/.kube/config
Unable to connect to the server: x509: certificate signed by unknown authority Wrong CA certificate in kubeconfig Check certificate-authority-data matches the cluster CA
error: You must be logged in to the server (Unauthorized) Wrong or expired credentials Check user cert/token, regenerate if needed
error: no configuration has been provided Empty or missing kubeconfig Verify file exists and is valid YAML
Context exists but wrong namespace Default namespace not set kubectl config set-context --current --namespace=<ns>

4.2 Decoding Embedded Certificates

1
2
3
4
5
6
7
8
# Extract and decode the CA certificate
kubectl config view --raw -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' | base64 -d | openssl x509 -text -noout

# Extract and decode the client certificate
kubectl config view --raw -o jsonpath='{.users[0].user.client-certificate-data}' | base64 -d | openssl x509 -text -noout

# Check certificate expiration
kubectl config view --raw -o jsonpath='{.users[0].user.client-certificate-data}' | base64 -d | openssl x509 -noout -dates

4.3 Identifying the Current User

1
2
3
4
5
6
7
8
# Who am I?
kubectl auth whoami    # Kubernetes 1.28+

# Or check the current context's user
kubectl config view -o jsonpath='{.contexts[?(@.name=="'$(kubectl config current-context)'")].context.user}'

# Quick check — what can I do?
kubectl auth can-i --list

5. CKA Exam Context Workflow

The exam environment has multiple clusters pre-configured. Each question specifies which context to use.

5.1 Exam Pattern

1
2
3
4
5
6
7
Question 1:
  Context: kubectl config use-context k8s-cluster1
  Task: Create a deployment...

Question 2:
  Context: kubectl config use-context k8s-cluster2
  Task: Upgrade the cluster...
# Step 1: Switch context (ALWAYS do this first)
kubectl config use-context <context-from-question>

# Step 2: Verify you're on the right cluster
kubectl config current-context
kubectl get nodes

# Step 3: Set namespace if the question specifies one
kubectl config set-context --current --namespace=<namespace>

# Step 4: Do the task

5.3 Aliases for Speed

Add to your .bashrc at the start of the exam:

1
2
3
4
5
6
7
8
9
alias k=kubectl
alias kgc='kubectl config get-contexts'
alias kuc='kubectl config use-context'
alias kns='kubectl config set-context --current --namespace'

# Usage:
kuc k8s-cluster1
kns kube-system
k get pods

6. Practice Exercises

Exercise 1 — Explore Your Kubeconfig

# 1. View your current kubeconfig
kubectl config view

# 2. What is the current context?
kubectl config current-context

# 3. List all contexts
kubectl config get-contexts

# 4. What server is the current cluster pointing to?
kubectl config view -o jsonpath='{.clusters[0].cluster.server}'

# 5. What user is the current context using?
kubectl config view -o jsonpath='{.contexts[0].context.user}'

Exercise 2 — Create and Switch Contexts

# 1. Create a new context that uses the existing cluster and user but defaults to kube-system
kubectl config set-context kube-system-context \
  --cluster=$(kubectl config view -o jsonpath='{.clusters[0].name}') \
  --user=$(kubectl config view -o jsonpath='{.users[0].name}') \
  --namespace=kube-system

# 2. Switch to it
kubectl config use-context kube-system-context

# 3. Verify — pods should be from kube-system without -n flag
kubectl get pods

# 4. Switch back to the original context
kubectl config use-context <original-context>

# 5. Clean up
kubectl config delete-context kube-system-context

Exercise 3 — Build a Kubeconfig from Scratch

# 1. Create an empty kubeconfig file
export KUBECONFIG=/tmp/test-kubeconfig

# 2. Add a cluster
kubectl config set-cluster test-cluster \
  --server=https://127.0.0.1:6443 \
  --certificate-authority=/etc/kubernetes/pki/ca.crt

# 3. Add a user
kubectl config set-credentials test-user \
  --client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt \
  --client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key

# 4. Create a context
kubectl config set-context test-context \
  --cluster=test-cluster \
  --user=test-user \
  --namespace=default

# 5. Set it as current
kubectl config use-context test-context

# 6. View the result
kubectl config view

# 7. Test connectivity
kubectl get nodes

# 8. Clean up
unset KUBECONFIG
rm /tmp/test-kubeconfig

Exercise 4 — Merge Multiple Kubeconfigs

# 1. Copy the admin kubeconfig to a second file with modifications
cp $HOME/.kube/config /tmp/second-config

# 2. Edit /tmp/second-config — rename the context, cluster, and user
#    (use kubectl config rename-context or edit manually)

# 3. Merge both files
export KUBECONFIG=$HOME/.kube/config:/tmp/second-config

# 4. List all contexts — you should see contexts from both files
kubectl config get-contexts

# 5. Switch between them
kubectl config use-context <context-from-second-file>

# 6. Clean up
unset KUBECONFIG
rm /tmp/second-config

Exercise 5 — Troubleshoot a Broken Kubeconfig

# 1. Create a broken kubeconfig
cat <<EOF > /tmp/broken-config
apiVersion: v1
kind: Config
clusters:
- name: broken-cluster
  cluster:
    server: https://127.0.0.1:9999
    certificate-authority-data: dGhpcyBpcyBub3QgYSByZWFsIGNlcnQ=
users:
- name: broken-user
  user:
    token: invalid-token
contexts:
- name: broken-context
  context:
    cluster: broken-cluster
    user: broken-user
current-context: broken-context
EOF

# 2. Try to use it
kubectl get nodes --kubeconfig=/tmp/broken-config
# Observe the error

# 3. Fix it:
#    - Correct the server address
#    - Fix the CA certificate
#    - Provide valid credentials

# 4. Clean up
rm /tmp/broken-config

7. Key Takeaways for the CKA Exam

Point Detail
Always switch context first kubectl config use-context <name> at the start of every question
Set default namespace kubectl config set-context --current --namespace=<ns> saves typing -n
Know the file structure clusters + users + contexts + current-context
Default path $HOME/.kube/config, overridden by KUBECONFIG env var or --kubeconfig flag
kubectl config view Shows the merged kubeconfig (redacted); add --raw for full secrets
Imperative config commands set-cluster, set-credentials, set-context, use-context, delete-context
KUBECONFIG merging Colon-separated paths merge all files; --flatten writes a single merged file
localhost:8080 refused Means no kubeconfig is loaded — check the file path and env var
Exam aliases Set up alias k=kubectl and context-switching shortcuts at exam start

Previous: 05-rbac.md — RBAC

Next: 07-pods-and-workloads.md — Pods & Workloads