kr8s

0.20.15 · active · verified Sun Apr 12

kr8s is a simple, extensible Python client library for Kubernetes, designed to feel familiar for users accustomed to `kubectl`. It provides a high-level API for interacting with Kubernetes clusters, offering both synchronous and asynchronous interfaces. The library abstracts away many low-level API details, focusing on developer experience and ease of use for scripting, automation, and building Kubernetes operators. It is actively maintained with regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic synchronous interaction with a Kubernetes cluster using `kr8s`. It retrieves a list of nodes, creates a simple Nginx pod, waits for it to become ready, and then deletes it. kr8s automatically uses your existing kubeconfig for authentication, similar to `kubectl`.

import kr8s

# Connect to the Kubernetes API (uses kubeconfig by default)
# Equivalent to 'kubectl get nodes'

try:
    # Synchronous API
    nodes = kr8s.get("nodes")
    print("Synchronous API - Nodes found:")
    for node in nodes:
        print(f"- {node.name}")

    # Example using a specific object type and creating one
    from kr8s.objects import Pod

    # Define a simple Pod specification as a Python dictionary
    pod_manifest = {
        "apiVersion": "v1",
        "kind": "Pod",
        "metadata": {
            "name": "my-test-pod",
            "labels": {"app": "my-app"}
        },
        "spec": {
            "containers": [
                {"name": "nginx", "image": "nginx:latest"}
            ]
        }
    }

    print(f"\nAttempting to create pod: {pod_manifest['metadata']['name']}")
    test_pod = Pod(pod_manifest)
    test_pod.create()
    print(f"Pod '{test_pod.name}' created in namespace '{test_pod.namespace}'.")

    # Wait for the pod to be ready (optional)
    print("Waiting for pod to be ready...")
    test_pod.wait(conditions=["Ready"], timeout=60)
    print("Pod is ready!")

    # Clean up the pod
    print(f"\nDeleting pod: {test_pod.name}")
    test_pod.delete(cascade=True)
    print("Pod deleted.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Ensure you have a running Kubernetes cluster and valid kubeconfig configured (e.g., `minikube start`).")

view raw JSON →