Skip to content

KeyError: 'current-context' when passing context= to api() and kubeconfig has no current-context #737

@ajcasagrande

Description

@ajcasagrande

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

  1. Ensure your kubeconfig has no current-context set (kubectl config unset current-context)
  2. 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 here

The fix would be to resolve the namespace from self._context (which was already correctly set above) rather than going through current_namespacecurrent_context again. Something like:

if self._namespace is None:
    self._namespace = self._context.get("namespace", "default")

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions