ahmetb/kubectx · error
failed to query namespace %q from k8s API: %w
Error message
failed to query namespace %q from k8s API: %w
What it means
namespaceExists wraps any error other than 'not found' returned by the k8s API when querying a Namespace object via clientset.CoreV1().Namespaces().Get. It is raised to distinguish a legitimate missing namespace (returns false, nil) from a real API failure (auth, connectivity, permissions), so callers like switchNamespace fail loudly with the underlying cause preserved via %w.
Source
Thrown at cmd/kubens/switch.go:117
}
func namespaceExists(kc *kubeconfig.Kubeconfig, ns string) (bool, error) {
// for tests
if os.Getenv("_MOCK_NAMESPACES") != "" {
return ns == "ns1" || ns == "ns2", nil
}
clientset, err := newKubernetesClientSet(kc)
if err != nil {
return false, fmt.Errorf("failed to initialize k8s REST client: %w", err)
}
namespace, err := clientset.CoreV1().Namespaces().Get(context.Background(), ns, metav1.GetOptions{})
if errors2.IsNotFound(err) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("failed to query namespace %q from k8s API: %w", ns, err)
}
return namespace != nil, nil
}
View on GitHub (pinned to 12ad6fb22e)
Solutions
- Verify cluster connectivity: kubectl cluster-info with the same kubeconfig used by the tool.
- Check credentials are fresh: re-login (e.g. kubectl oidc-login, cloud provider auth) or refresh the service-account token.
- Confirm RBAC: run kubectl get namespace <ns> as the same user; ask an admin for 'get' on 'namespaces' if forbidden.
- Confirm KUBECONFIG/current-context points to the intended cluster endpoint and port.
Example fix
// before: proceeding without checking API access
err := switchNamespace(clientset, "prod")
// after: pre-flight namespace check with clear diagnostics
if exists, err := namespaceExists(clientset, "prod"); err != nil {
return fmt.Errorf("cannot switch: %w", err)
} else if !exists {
return fmt.Errorf("namespace %q does not exist", "prod")
} Defensive patterns
Strategy: try-catch
Validate before calling
// Go: verify API reachability and auth before switching
if _, err := clientset.Discovery().ServerVersion(); err != nil {
return fmt.Errorf("cluster unreachable: %w", err)
} Type guard
// Go: use apierrors to narrow the failure kind
if apierrors.IsNotFound(err) { /* namespace absent, not an API failure */ }
if apierrors.IsForbidden(err) { /* RBAC issue */ } Try / catch
exists, err := namespaceExists(clientset, ns)
if err != nil {
var apiErr *apierrors.StatusError
if errors.As(err, &apiErr) && apiErr.ErrStatus.Reason == metav1.StatusReasonForbidden {
return fmt.Errorf("no permission to read namespaces: %w", err)
}
return fmt.Errorf("cluster query failed, check connectivity/credentials: %w", err)
} Prevention
- Run kubectl cluster-info as a pre-flight in scripts before switching namespaces.
- Keep credentials refreshed (token rotation / re-login) for cloud clusters.
- Grant 'get namespaces' RBAC to service accounts used by automation.
- Pin KUBECONFIG per script to avoid silently querying the wrong cluster.
When it happens
Trigger: Any non-NotFound error from Namespaces().Get in namespaceExists: an invalid or unreadable kubeconfig, unreachable API server, expired/stale credentials, or RBAC denial (namespaces cannot get). Raised in namespaceExists, called by switchNamespace in cmd/kubens/switch.go:117.
Common situations: VPN disconnected so the cluster endpoint is unreachable; kubeconfig points to a wrong port or old cluster; service account token expired; user lacks 'get namespaces' RBAC permission on restricted clusters.
Related errors
- failed to read namespace of "%s": %w
- failed to switch namespace: %w
- kubeconfig error: %w
- failed to get current context: %w
- kubeconfig error: %w
AI-assisted analysis of ahmetb/kubectx@12ad6fb22e (2026-09-02).
Data as JSON: /api/errors/32298513442e973f.
Report an issue: GitHub.