Pykube-ng
Pykube-ng is a lightweight Python 3.6+ client library for Kubernetes, providing a Python-native way to interact with the Kubernetes API. It's a community-maintained fork of the unmaintained `kelproject/pykube` library, focusing on simplicity and direct object interaction. The current stable version is 23.6.0, with releases occurring periodically to maintain compatibility and add features.
Warnings
- breaking Python 2.7 compatibility was removed in version 0.17 when the project was forked to `pykube-ng`. Users migrating from `kelproject/pykube` must use Python 3.6+.
- gotcha The `HTTPClient` object is explicit and needs to be passed to object queries and methods. There is no implicit global configuration like in some other Kubernetes clients.
- gotcha Watch calls (e.g., `object.watch()`) terminate after a connection is lost (e.g., due to network issues or API server restarts). `pykube-ng` does not include internal reconnection logic or an automatic `while True` loop.
- gotcha The `APIObject.update()` method can fail if the resource was modified concurrently between being loaded and being updated, leading to a conflict. This is a common pattern in Kubernetes for optimistic concurrency.
Install
-
pip install pykube-ng
Imports
- HTTPClient
from pykube import HTTPClient
- KubeConfig
from pykube import KubeConfig
- Deployment
from pykube import Deployment
- Pod
from pykube import Pod
- all
from pykube import all
Quickstart
import pykube
# KubeConfig.from_env() attempts to load config from in-cluster service account or ~/.kube/config
config = pykube.KubeConfig.from_env()
api = pykube.HTTPClient(config)
# List all pods in all namespaces
pods = pykube.Pod.objects(api, namespace=pykube.all)
print(f"Found {len(list(pods))} pods across all namespaces:")
for pod in pods:
print(f" {pod.namespace}/{pod.name} (Status: {pod.obj['status']['phase']})")
# Get a specific deployment (replace 'my-deployment' and 'default' with actual values)
try:
deployment = pykube.Deployment.objects(api).get(name="my-deployment", namespace="default")
print(f"\nFound deployment: {deployment.name} in namespace {deployment.namespace}")
except pykube.exceptions.ObjectDoesNotExist:
print("\nDeployment 'my-deployment' not found in 'default' namespace.")