-
Notifications
You must be signed in to change notification settings - Fork 65
KeyError: 'current-context' when passing context= to api() and kubeconfig has no current-context #737
Description
Description
When calling kr8s.asyncio.api(context="my-context") with a kubeconfig file that has no current-context field set, kr8s raises an unhandled KeyError: 'current-context' instead of using the explicitly provided context.
Version
kr8s 0.20.15, Python 3.12
Reproduction
- Ensure your kubeconfig has no
current-contextset (kubectl config unset current-context) - Run:
import asyncio
import kr8s.asyncio
async def main():
api = await kr8s.asyncio.api(context="some-valid-context")
print(await api.async_version())
asyncio.run(main())Traceback
File "kr8s/_auth.py", line 160, in _load_kubeconfig
self._namespace = self.kubeconfig.current_namespace
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "kr8s/_config.py", line 112, in current_namespace
return self.get_context(self.current_context).get("namespace", "default")
^^^^^^^^^^^^^^^^^^^^
File "kr8s/_config.py", line 107, in current_context
return self._configs[0].current_context
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "kr8s/_config.py", line 264, in current_context
return self._raw["current-context"]
~~~~~~~~~^^^^^^^^^^^^^^^^^^^
KeyError: 'current-context'
Root cause
In _auth.py:_load_kubeconfig, lines 145-156 correctly handle the context parameter — when self._use_context is set, it uses that instead of current_context. However, line 160 unconditionally accesses self.kubeconfig.current_namespace, which internally reads current_context from the raw kubeconfig dict regardless of whether an explicit context was provided.
# Lines 145-156 handle the context correctly:
if self._use_context:
self._context = self.kubeconfig.get_context(self._use_context)
self.active_context = self._use_context
elif self.kubeconfig.current_context: # This would also KeyError, but is guarded by the if above
...
# But line 160 ignores the resolved context and goes back to current_context:
if self._namespace is None:
self._namespace = self.kubeconfig.current_namespace # <-- crashes hereThe fix would be to resolve the namespace from self._context (which was already correctly set above) rather than going through current_namespace → current_context again. Something like:
if self._namespace is None:
self._namespace = self._context.get("namespace", "default")