ConfigException: Invalid kube-config file (kubernetes python client)
Fixes the Kubernetes Python client rejecting your kubeconfig. Use when config.load_kube_config() raises ConfigException. Not for API 401 errors (those mean the config loaded but auth failed).
TL;DR: The Python client is not reading the kubeconfig you think it is, or the file is malformed. Set KUBECONFIG to the right file (or fix current-context in it), and loadkubeconfig works.
kubernetes.config.config_exception.ConfigException: Invalid kube-config file. Expected key current-context in kube-configFix it
- Check which file kubectl uses: kubectl config view --minify. Expected: valid output with a current-context.
- Point the client at the same file: export KUBECONFIG to that path, or pass configfile= explicitly to loadkube_config. Expected: no more ConfigException.
- If the file itself is bad, fix current-context to name an existing context: kubectl config get-contexts, then kubectl config use-context [name]. Expected: kubectl config current-context prints the name.
- Verify from Python: python -c "from kubernetes import config; config.loadkubeconfig(); print('ok')". Expected: ok.
When this applies
- loadkubeconfig() raises ConfigException.
- kubectl works but the Python client does not (different file being read).
When it doesn't
- The error is ApiException 401: the config loaded; the cluster rejected your credentials.
- Running inside a pod: use config.loadinclusterconfig() instead.
Compatibility
- kubernetes client any version.
Why it happens
kubectl merges ~/.kube/config with KUBECONFIG, while the Python client defaults to ~/.kube/config only. A KUBECONFIG env var set for kubectl, or a malformed file kubectl tolerates, breaks the client.
Edge cases
- Multiple documents or Windows CRLF line endings can trip the YAML parser; normalize the file.
- In CI, write the kubeconfig from a secret to a temp file and pass config_file= explicitly.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.