VMware ESXi and vSphere Cluster Management
Kubeconfig: Configure Kubernetes Cluster Access
Learn how kubeconfig stores Kubernetes clusters, users, contexts, credentials, namespaces, and TLS settings, plus how to inspect, merge, create, switch, and troubleshoot kubectl configurations.
What Is a Kubeconfig?
A kubeconfig is a client-side configuration document used by Kubernetes tools such as kubectl. It tells a client where the Kubernetes API server is, how to authenticate, which cluster and identity to use together, and which context should be selected by default.
A kubeconfig is different from both a Kubernetes resource manifest and in-cluster service account configuration:
- Kubeconfig: configures an external client such as
kubectlrunning on a workstation, bastion host, or CI runner. - Resource manifest: describes objects to create or change in Kubernetes, such as Deployments, Services, and ConfigMaps.
- In-cluster service account configuration: is made available to software running inside a Pod, commonly through a mounted token and cluster CA. It is not normally the same file used by a workstation's
kubectl.
Unless another location is selected, kubectl normally reads ~/.kube/config. The KUBECONFIG environment variable can select one or more alternative files.
Kubeconfig Structure
A kubeconfig is YAML. Its top-level kind is usually Config, and its apiVersion is commonly v1. The most important data is split into named cluster, user, and context entries.
| Field | Purpose | Typical contents | Security considerations |
|---|---|---|---|
apiVersion | Identifies the configuration API version. | v1 | Use a version supported by the client. |
kind | Identifies the document type. | Config | Not usually secret itself. |
clusters | Names API server and trust settings. | Server URL and CA data or file. | Endpoint metadata can reveal internal infrastructure. |
users | Names authentication identities or methods. | Certificates, token, or exec plugin. | Often contains credentials or references to them. |
contexts | Combines a cluster, user, and optional namespace. | dev-team using dev-cluster. | Names can make production targets look similar to test targets. |
current-context | Selects the default context. | dev-team | Wrong values can send commands to the wrong cluster. |
preferences | Reserved client preference settings. | Usually empty. | Keep only recognized settings. |
extensions | Allows additional client-specific data. | Tool-specific extension objects. | Review unfamiliar data before sharing. |
Clusters, Users, and Contexts
| Object type | What it defines | Referenced by | Common examples |
|---|---|---|---|
| Cluster | The Kubernetes API server address and TLS trust configuration. | Contexts. | dev-cluster, production-cluster. |
| User | An authentication entry. The name represents credentials, not necessarily a human. | Contexts. | developer, ci-deployer. |
| Context | A named association of one cluster and one user, optionally with a namespace. | current-context or --context. | dev-team, prod-readonly. |
For example, a context can bind the developer user to dev-cluster and default to the payments namespace. The current-context field determines which context is used when a command does not specify another one.
apiVersion: v1
kind: Config
clusters:
- name: dev-cluster
cluster:
server: https://api.dev.example.com:6443
certificate-authority-data: <base64-encoded-ca-certificate>
users:
- name: developer
user:
exec:
apiVersion: client.authentication.k8s.io/v1
command: credential-helper
contexts:
- name: dev-team
context:
cluster: dev-cluster
user: developer
namespace: default
current-context: dev-team
How kubectl Selects Configuration
Configuration selection has two related decisions: which kubeconfig file or files to read, and which cluster, user, and namespace to use from the resulting configuration.
| Mechanism | Example | When it applies | Effect on selected configuration |
|---|---|---|---|
--kubeconfig | kubectl --kubeconfig=./team.yaml get pods | For one command or an explicitly configured invocation. | Selects the named file and takes precedence over KUBECONFIG. |
KUBECONFIG | export KUBECONFIG="$HOME/.kube/config:$HOME/.kube/team-config" | When no --kubeconfig flag is supplied. | Loads one or more files, separated by the platform's path-list separator. |
| Default path | ~/.kube/config | When neither explicit selection nor KUBECONFIG is supplied. | Uses the normal per-user configuration file. |
--context | kubectl --context=production get nodes | For one command. | Overrides current-context. |
--cluster and --user | kubectl --cluster=dev-cluster --user=developer get pods | For one command when supported by the command. | Override the cluster or user selected through the context. |
--namespace | kubectl --namespace=payments get pods | For namespaced commands. | Overrides the context's default namespace for that command. |
For a normal command, kubectl first chooses the configuration source, then uses the explicitly supplied context or the file's current-context. The selected context supplies the cluster, user, and default namespace. Explicit cluster, user, and namespace flags override those context values.
When KUBECONFIG contains multiple files, clients combine them. Earlier files generally take precedence when the same named entry appears more than once, so duplicate names can hide an entry from a later file. The exact result also depends on which fields are present, so use kubectl config view to inspect the effective result.
Daily Context Management
Inspect the Active Target
kubectl config current-context
kubectl config get-contexts
kubectl config view --minify
get-contexts lists available contexts. current-context prints the saved default. view --minify shows the configuration relevant to the current context instead of every configured cluster and identity. Review the displayed cluster, user, and namespace before risky operations.
Switch or Override a Context
kubectl config use-context dev-team
kubectl config set-context --current --namespace=payments
kubectl --context=production --namespace=payments get pods
use-context changes the saved current context. Setting a namespace on the current context also changes the saved default. In contrast, --context and --namespace are temporary overrides for that invocation.
For production, prefer an explicit one-off command and verify it:
kubectl --context=production config current-context
kubectl --context=production --namespace=payments get pods
Use clear names such as prod-readonly, staging-deployer, and dev-team rather than ambiguous names such as admin or cluster1.
Authentication Methods
| Method | Relevant fields | Common use case | Rotation or expiry behavior | Security notes |
|---|---|---|---|---|
| Client certificate | client-certificate, client-key, or their -data forms. | Platform users, administrators, or automation. | Certificates and keys must be renewed before expiration. | Protect private keys; possession may grant the identity's permissions. |
| Bearer token | token or tokenFile. | Short-lived identity tokens or controlled automation. | Tokens may expire, be revoked, or rotate. | Do not place tokens in repositories, screenshots, or shell history. |
| Exec credential plugin | exec, including command and plugin API version. | Cloud providers and external SSO or identity systems. | The plugin obtains or refreshes credentials dynamically. | Trust the executable and inspect its installation and permissions. |
| Legacy auth provider | auth-provider. | Older client or provider integrations. | Provider-specific refresh behavior. | Legacy pattern; modern exec plugins are generally preferred. |
| Basic authentication | username and password. | Older systems only. | Password changes invalidate access. | Discouraged because static passwords are difficult to protect and rotate safely. |
An exec credential plugin is an external command that kubectl invokes when it needs credentials. If the command is missing, not executable, misconfigured, or unable to contact its identity provider, authentication fails even though the kubeconfig structure is valid.
TLS and Cluster Trust
Each cluster entry has a server value such as https://api.example.com:6443. It may also identify the certificate authority used to verify the API server:
certificate-authoritypoints to a CA certificate file.certificate-authority-dataembeds base64-encoded CA certificate data in the kubeconfig.insecure-skip-tls-verify: truedisables certificate verification.
Disabling verification is unsafe because a client can no longer reliably confirm that it is talking to the intended API server. Use it only for tightly controlled troubleshooting, never as a routine production fix.
An x509 hostname error commonly means the server name in the URL is not included in the API server certificate's valid names. An unknown-authority error commonly means the configured CA is missing, incorrect, outdated, or does not belong to the server being contacted.
Creating and Editing Entries
The kubectl config commands update the selected kubeconfig source. Make a backup before changing an important file, and ensure the file is writable.
kubectl config set-cluster dev-cluster \
--server=https://api.dev.example.com:6443 \
--certificate-authority=ca.crt
kubectl config set-credentials developer \
--client-certificate=developer.crt \
--client-key=developer.key
kubectl config set-context dev-team \
--cluster=dev-cluster \
--user=developer \
--namespace=default
kubectl config use-context dev-team
kubectl config set-context --current --namespace=payments
These commands create or replace named entries. A cluster entry identifies the endpoint and trust material. A user entry identifies credentials. A context binds the two and can store a default namespace.
Manual YAML editing is appropriate when reviewing a generated configuration, repairing a carefully understood value, or integrating a configuration into a controlled provisioning process. Preserve valid YAML indentation and quoting. Do not corrupt base64-encoded certificate or key data, and validate the result with kubectl config view before using it.
Managing Multiple Kubeconfig Files
Separate files are useful when teams, environments, cloud accounts, or privilege levels must remain distinct. They reduce accidental mixing, but the active file list must be visible to the operator and to automation.
export KUBECONFIG="$HOME/.kube/config:$HOME/.kube/team-config"
kubectl config view
kubectl config get-contexts
To produce a self-contained combined file, merge and flatten the configuration:
kubectl config view --merge --flatten > merged-kubeconfig.yaml
chmod 600 merged-kubeconfig.yaml
kubectl --kubeconfig=./merged-kubeconfig.yaml config get-contexts
Flattening embeds referenced certificate and key data into the output. This makes the file portable, but it may also copy private keys, tokens, and other secrets into one highly sensitive file. Store it securely and delete it when no longer needed.
Duplicate cluster, user, or context names are dangerous. Depending on file order and merge rules, one entry can hide another or be selected unexpectedly. Use unique names that include environment and purpose, such as prod-eu1, prod-eu1-readonly, and staging-deployer.
Inspecting and Sharing Configuration Safely
kubectl config view
kubectl config view --minify
kubectl config view --raw
kubectl config get-contexts
kubectl config current-context
view --raw can reveal data that is normally hidden or transformed, including credential material. Treat its output as secret. Kubeconfig files commonly contain tokens, private keys, client certificates, identity-provider metadata, internal hostnames, and access patterns.
- Keep files readable only by the intended account, commonly with permissions such as
600. - Store them outside public repositories and untrusted shared directories.
- Do not paste raw output into support tickets, chat, shell history, screenshots, or issue trackers.
- Redact tokens, passwords, private keys, client certificate data, and sensitive endpoint details before sharing.
- Prefer a credential-free connection template containing only placeholder server and CA information when documentation is needed.
A shareable cluster template is not a working credential-bearing kubeconfig. A recipient still needs authorized credentials and an appropriate user entry.
Common Operational Workflows
Connect to a Newly Provisioned Cluster
- Obtain the cluster's API server address, trusted CA, and an identity issued by the cluster's authentication system.
- Place the provider-generated configuration at
~/.kube/config, select it with--kubeconfig, or add it toKUBECONFIG. - List contexts and select the intended one.
- Run a harmless request such as
kubectl cluster-infoor inspect the current configuration.
Move Between Environments
kubectl config use-context staging-deployer
kubectl config current-context
kubectl --context=production-readonly get nodes
For destructive commands, use an explicit context and namespace, and display the target immediately before the command. Automation should set --kubeconfig and --context explicitly rather than relying on a developer's shell defaults.
Use Short-Lived Cloud or SSO Credentials
Configure the user entry with the provider's supported exec plugin. The plugin can obtain a fresh token or certificate when kubectl runs. Credential expiration is expected; refresh through the identity provider workflow instead of copying long-lived secrets into the kubeconfig.
Create Least-Privilege Access
Create a user or automation identity with only the credentials it needs, then grant permissions through Kubernetes RBAC. Authentication identifies the caller; RBAC authorization determines whether that identity may perform an operation on a resource. A kubeconfig does not itself grant permissions.
Troubleshooting Kubeconfig Access
| Symptom | Likely cause | Verification command | Resolution |
|---|---|---|---|
| No configuration has been provided | Missing default file, incorrect --kubeconfig, or unavailable KUBECONFIG file. | echo "$KUBECONFIG"kubectl config view | Check file existence, readability, path-list separators, and the selected source. |
| Requested context does not exist | Typo, wrong file, incomplete merge, or name collision. | kubectl config get-contextskubectl config view | Use the exact context name and inspect file order and duplicate names. |
| Connection refused, DNS failure, or unreachable API server | Wrong server URL, stopped endpoint, unavailable network route, proxy, or DNS problem. | kubectl config view --minifykubectl cluster-info | Confirm the endpoint, network access, VPN or proxy requirements, and cluster availability. |
| x509 unknown authority | Missing, incorrect, or outdated CA data; changed or intercepted endpoint. | kubectl config view --minify | Install the correct CA or regenerate the provider configuration. Do not permanently use insecure TLS. |
| x509 hostname mismatch | The URL hostname is not covered by the API server certificate. | kubectl config view --minify | Use the endpoint name issued for the cluster and correct DNS or certificate configuration. |
| Unauthorized or credentials invalid | Expired token or client certificate, wrong user entry, or broken exec plugin. | kubectl config view --minifykubectl auth whoami | Confirm the selected user, refresh credentials, renew certificates, and verify the plugin is installed and executable. |
| Forbidden | Authentication succeeded, but RBAC denies the operation or namespace. | kubectl auth can-i get pods -n payments | Confirm context and namespace, then review applicable Roles, ClusterRoles, RoleBindings, and ClusterRoleBindings. |
| Commands use the wrong namespace | Context namespace differs from the intended namespace, or a namespace flag was omitted. | kubectl config view --minify | Use --namespace temporarily or set the context's saved namespace. |
| Commands affect the wrong cluster | Incorrect current-context, unexpected KUBECONFIG, or implicit automation defaults. | kubectl config current-contextecho "$KUBECONFIG" | Use explicit context and kubeconfig flags and adopt unambiguous names. |
A 401 Unauthorized response indicates an authentication problem: the API server could not accept the presented identity. A 403 Forbidden response indicates that authentication worked but RBAC authorization denied the requested action. Separating these cases prevents unnecessary credential replacement when the real problem is permissions.
Exam- and Operations-Relevant Notes
- Cluster, user, and context are separate: a context references names; it does not duplicate the complete cluster and user definitions.
current-contextis only the default:--contextcan select another context for one command.- Namespace is a default scope: it affects namespaced resources and can be overridden with
--namespace; cluster-scoped resources are not placed in a namespace. - Authentication is not authorization: credentials establish identity, while RBAC controls allowed actions.
certificate-authority-datais encoded, not automatically harmless: embedded certificates and especially embedded keys or tokens still require protection.- Insecure TLS is not a trust solution:
insecure-skip-tls-verifyremoves verification and should not be a permanent production setting. - Exec plugins are executable code: verify their source, path, and permissions before trusting them.
For a compact reference, see the kubeconfig guide.