Skip to main content
In this lesson, we’ll explore how Kubernetes kubeconfig files let you store cluster endpoints and user credentials for kubectl, eliminating the need to retype flags every time you interact with your cluster.

1. Direct API Access with curl

If your API server is at my-kube-playground:6443 and you’ve generated:
  • CA certificate: ca.crt
  • Client certificate: admin.crt
  • Client key: admin.key
You can query the API directly:
Response:

2. Equivalent kubectl Commands

With kubectl, the same request requires these flags:
Output:
Typing long flag lists is tedious. Let’s streamline this with a kubeconfig file.
By default, kubectl looks for ~/.kube/config. You can override with --kubeconfig=PATH.

3. Creating and Using a kubeconfig File

Save your cluster, user, and context definitions in a YAML file (e.g., config), then run:
Both commands will yield:

4. Structure of a kubeconfig File

A kubeconfig has three top-level sections:
The image is a diagram of a KubeConfig file structure, showing clusters, contexts, and users in separate sections. It illustrates how different environments and roles are organized within the configuration.

4.1 Minimal Example


5. Managing Multiple Clusters, Users, and Contexts

You can add as many entries as needed:

5.1 Viewing and Switching Contexts

Use built-in commands to inspect or switch contexts:

6. Setting a Default Namespace

Embed namespace in the context to avoid adding -n on every command:
Now kubectl get pods under this context defaults to the finance namespace.

7. Embedding Certificate Data Directly

Inline your certs and keys as base64 to avoid external files:
Generate and inspect base64 fields:
Embedding secrets directly in your config can increase exposure risk. Always secure your files and consider encryption at rest.

8. Practice Exercises

  1. Create a second context for a staging cluster.
  2. Switch between contexts without retyping server flags.
  3. Embed certificates and verify connectivity.
  4. Troubleshoot an invalid certificate scenario.

Watch Video

Practice Lab