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 kubectl running 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.

FieldPurposeTypical contentsSecurity considerations
apiVersionIdentifies the configuration API version.v1Use a version supported by the client.
kindIdentifies the document type.ConfigNot usually secret itself.
clustersNames API server and trust settings.Server URL and CA data or file.Endpoint metadata can reveal internal infrastructure.
usersNames authentication identities or methods.Certificates, token, or exec plugin.Often contains credentials or references to them.
contextsCombines a cluster, user, and optional namespace.dev-team using dev-cluster.Names can make production targets look similar to test targets.
current-contextSelects the default context.dev-teamWrong values can send commands to the wrong cluster.
preferencesReserved client preference settings.Usually empty.Keep only recognized settings.
extensionsAllows additional client-specific data.Tool-specific extension objects.Review unfamiliar data before sharing.

Clusters, Users, and Contexts

Object typeWhat it definesReferenced byCommon examples
ClusterThe Kubernetes API server address and TLS trust configuration.Contexts.dev-cluster, production-cluster.
UserAn authentication entry. The name represents credentials, not necessarily a human.Contexts.developer, ci-deployer.
ContextA 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.

MechanismExampleWhen it appliesEffect on selected configuration
--kubeconfigkubectl --kubeconfig=./team.yaml get podsFor one command or an explicitly configured invocation.Selects the named file and takes precedence over KUBECONFIG.
KUBECONFIGexport 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/configWhen neither explicit selection nor KUBECONFIG is supplied.Uses the normal per-user configuration file.
--contextkubectl --context=production get nodesFor one command.Overrides current-context.
--cluster and --userkubectl --cluster=dev-cluster --user=developer get podsFor one command when supported by the command.Override the cluster or user selected through the context.
--namespacekubectl --namespace=payments get podsFor 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

MethodRelevant fieldsCommon use caseRotation or expiry behaviorSecurity notes
Client certificateclient-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 tokentoken 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 pluginexec, 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 providerauth-provider.Older client or provider integrations.Provider-specific refresh behavior.Legacy pattern; modern exec plugins are generally preferred.
Basic authenticationusername 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-authority points to a CA certificate file.
  • certificate-authority-data embeds base64-encoded CA certificate data in the kubeconfig.
  • insecure-skip-tls-verify: true disables 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

  1. Obtain the cluster's API server address, trusted CA, and an identity issued by the cluster's authentication system.
  2. Place the provider-generated configuration at ~/.kube/config, select it with --kubeconfig, or add it to KUBECONFIG.
  3. List contexts and select the intended one.
  4. Run a harmless request such as kubectl cluster-info or 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

SymptomLikely causeVerification commandResolution
No configuration has been providedMissing 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 existTypo, wrong file, incomplete merge, or name collision.kubectl config get-contexts
kubectl config view
Use the exact context name and inspect file order and duplicate names.
Connection refused, DNS failure, or unreachable API serverWrong server URL, stopped endpoint, unavailable network route, proxy, or DNS problem.kubectl config view --minify
kubectl cluster-info
Confirm the endpoint, network access, VPN or proxy requirements, and cluster availability.
x509 unknown authorityMissing, incorrect, or outdated CA data; changed or intercepted endpoint.kubectl config view --minifyInstall the correct CA or regenerate the provider configuration. Do not permanently use insecure TLS.
x509 hostname mismatchThe URL hostname is not covered by the API server certificate.kubectl config view --minifyUse the endpoint name issued for the cluster and correct DNS or certificate configuration.
Unauthorized or credentials invalidExpired token or client certificate, wrong user entry, or broken exec plugin.kubectl config view --minify
kubectl auth whoami
Confirm the selected user, refresh credentials, renew certificates, and verify the plugin is installed and executable.
ForbiddenAuthentication succeeded, but RBAC denies the operation or namespace.kubectl auth can-i get pods -n paymentsConfirm context and namespace, then review applicable Roles, ClusterRoles, RoleBindings, and ClusterRoleBindings.
Commands use the wrong namespaceContext namespace differs from the intended namespace, or a namespace flag was omitted.kubectl config view --minifyUse --namespace temporarily or set the context's saved namespace.
Commands affect the wrong clusterIncorrect current-context, unexpected KUBECONFIG, or implicit automation defaults.kubectl config current-context
echo "$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-context is only the default: --context can 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-data is 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-verify removes 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.