Registry / devops / kr8s
library0.20.15pypypi✓ verified 22d ago

kr8s is a simple, extensible Python client library for Kubernetes, designed to feel familiar to users of `kubectl`. It provides both synchronous and asynchronous APIs, sensible defaults, and utilities for common Kubernetes operations like listing, creating, and managing resources, as well as features like port forwarding and exec. It aims to reduce boilerplate and directly abstracts `kubeconfig` for authentication. The current version is 29.0.9.

pip install kr8s
INSTALL
IMPORT
SIG · KR8S
K
kr8s
devopspythonv0.20.15
Install
3.8s avg
Import
1742ms
Disk
51MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.20.15 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 1.778s · 44.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.8s · import 1.706s · 63MB
51MB installed
● package 51MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

kr8s
import kr8s
For the main client API and top-level functions.
Pod
from kr8s.objects import Pod
For working with specific Kubernetes object models (e.g., Pod, Deployment, Service).
asyncio_kr8s
import kr8s.asyncio as asyncio_kr8s
import kr8s.asyncio
Aliasing 'kr8s.asyncio' is common to avoid naming conflicts with the synchronous 'kr8s' module or other asyncio-related imports.

This quickstart demonstrates how to list Kubernetes nodes and create/delete a simple Pod using kr8s. It highlights the library's `kubectl`-like API for interacting with cluster resources and the automatic `kubeconfig` authentication. The example includes error handling for scenarios where a Kubernetes cluster is not accessible or permissions are insufficient.

import kr8s import os # kr8s automatically loads kubeconfig from default paths or KUBECONFIG env var # No explicit authentication is typically needed if kubectl is configured. # Example 1: List all nodes print("Listing nodes:") for node in kr8s.get("nodes"): print(f"- {node.name}") # Example 2: Create a simple Pod (requires cluster access) # This is a simplified example; in a real scenario, check for existence first. # Using os.environ.get for image to simulate configurable inputs. from kr8s.objects import Pod pod_manifest = { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "my-example-pod", "labels": {"app": "my-example"} }, "spec": { "containers": [{ "name": "nginx", "image": os.environ.get('K8_POD_IMAGE', 'nginx:latest') }] } } try: print("\nCreating pod 'my-example-pod'...") pod = Pod(pod_manifest) pod.create() print(f"Pod 'my-example-pod' created in namespace '{pod.namespace}'.") print("\nListing pods with label 'app=my-example':") selector = {'app': 'my-example'} for p in kr8s.get("pods", label_selector=selector): print(f"- {p.name} (Namespace: {p.namespace}, Status: {p.status.phase})") # Clean up (requires cluster access) print("\nDeleting pod 'my-example-pod'...") pod.delete() print("Pod 'my-example-pod' deleted.") except Exception as e: print(f"An error occurred: {e}") print("Make sure you have a running Kubernetes cluster and kubectl is configured.") print("If running locally, ensure your KUBECONFIG is set or ~/.kube/config exists.") print("For creating pods, ensure you have appropriate RBAC permissions.")
kr8s --version
Debug
Known issues
gotchakr8s aims for a `kubectl`-like experience, which means its API may not directly mirror the Kubernetes REST API's 1:1 object structure (unlike some auto-generated clients). This can lead to different import paths and object interaction patterns if you're accustomed to other Kubernetes Python clients.
fix
Familiarize yourself with the `kr8s` Client API and Object API documentation, which prioritizes ease of use and common `kubectl` operations over direct API mapping. Leverage `kr8s.get()` for flexible resource retrieval and `kr8s.objects` for common resource types.
affects: All versions
gotchaWhile `kr8s` automatically handles authentication using standard `kubeconfig` paths or the `KUBECONFIG` environment variable, explicit manual configuration is also possible. Users expecting to always manually configure client credentials might find this implicit behavior surprising, particularly in environments where multiple configurations exist.
fix
Understand the `kr8s` authentication lookup order (typically `~/.kube/config` then `/var/run/secrets/kubernetes.io/serviceaccount`). If explicit authentication is required, pass credentials or a specific `kubeconfig` path directly to `kr8s.api()`.
affects: All versions
gotchaFor performance-critical operations involving large result sets or when only simple metadata is needed, retrieving raw dictionaries using `raw=True` in `kr8s.get()` can be significantly faster than working with `APIObject` instances due to reduced processing overhead.
fix
When fetching resources, consider using `kr8s.get(..., raw=True)` if you only need the raw dictionary representation of Kubernetes objects and do not require the convenience methods provided by `kr8s.objects.APIObject`.
affects: All versions
breakingAPI compatibility with newer Kubernetes versions might break at some point, although the library aims for minimal changes. Users should be aware that their scripts might require minor tweaks when upgrading Kubernetes cluster versions.
fix
Regularly check the `kr8s` release notes and documentation for compatibility updates with new Kubernetes versions. Plan for minor code adjustments when upgrading your Kubernetes cluster to a new major version, especially if using less common API features.
affects: Future major Kubernetes version upgrades
Errors
Common errors & fixes
kubeconfig file not found
kr8s, like kubectl, relies on a kubeconfig file to connect to a Kubernetes cluster, and this error indicates that the file is missing from its expected locations (e.g., ~/.kube/config or the path specified by the KUBECONFIG environment variable).
fix
Ensure a valid kubeconfig file exists at ~/.kube/config, or set the KUBECONFIG environment variable to the correct path. You may need to obtain this file from your cluster administrator or generate it if you're running locally (e.g., minikube).
SyntaxError: 'await' outside async function
This Python error occurs when attempting to use the `await` keyword with kr8s's asynchronous API (kr8s.asyncio) in a regular, synchronous function, as `await` can only be used inside a function defined with `async def`.
fix
If using kr8s.asyncio, define your function with `async def` and run it using an asyncio event loop (e.g., `asyncio.run(your_async_function())`). Alternatively, use kr8s's default synchronous API which does not require `async/await`.
kr8s.NotFoundError: Unable to find the requested resource
This exception is raised by kr8s when it queries the Kubernetes API server for a specific resource (e.g., a Pod, Deployment, or Service) by name or kind, and that resource does not exist in the specified namespace or cluster.
fix
Verify that the resource kind and name are correct, and that it exists in the target namespace (or if `namespace=kr8s.ALL` is used for cluster-wide search). Check for typos in the resource name or kind, and ensure the resource is actually deployed in the cluster.
Client error '401 Unauthorized'
This error indicates that the kr8s client attempted to communicate with the Kubernetes API server but lacked the necessary authentication credentials or that the provided credentials (e.g., token, certificate) are invalid or expired.
fix
Check your kubeconfig file for valid credentials and ensure the context is correctly set. If using a service account token, verify it's current. If tokens are expiring (e.g., after an hour), investigate reauthentication mechanisms or token refresh.
KeyError: 'current-context' when passing context= to api() and kubeconfig has no current-context
This specific KeyError occurs when kr8s tries to access the 'current-context' key in a kubeconfig file that is either malformed or explicitly does not have a 'current-context' field defined, especially when manually specifying a `context` to `kr8s.api()`.
fix
Ensure your kubeconfig file is well-formed and has a `current-context` defined, or explicitly specify the `kubeconfig` parameter in `kr8s.api()` to point to a valid configuration file. If a specific context is needed, ensure it exists in the kubeconfig.
Upgrade
Version history
0.20.15latest on PyPI · released Jan 16, 2026
Audit
Dependencies
pythonrequiredRequired for library execution.
Agent activity
11 hits · last 30 days
node
8
OpenAI (training)
1
Resources
kr8s — pip install kr8s · libregistry