Kubernetes Python API Example

The Kubernetes Python API allows you to interact with Kubernetes clusters programmatically using Python. This API lets you create, modify, and manage Kubernetes resources directly from your Python scripts, such as pods, services, deployments, and more. To interact with Kubernetes using the Python API, you can use the official kubernetes Python client library. Here’s an overview of how to use it:

  1. Install the Kubernetes Python Client:
    Install the Kubernetes package using pip:
pip install kubernetes
  1. Import Required Modules:
    Import the necessary modules from the Kubernetes package to work with the Kubernetes Python API:
from kubernetes import client, config
  1. Load Kubernetes Configuration:
    The Kubernetes Python client library needs access to your Kubernetes cluster’s configuration. You can load it from a kubeconfig file or from the cluster’s environment variables:
config.load_kube_config()  # Load from kubeconfig file
# OR
config.load_incluster_config()  # Load from environment variables in a Kubernetes pod
  1. Create Kubernetes API Client:
    Create an instance of the Kubernetes API client:
v1 = client.CoreV1Api()
  1. Interact with Kubernetes Resources:
    You can use the API client to perform various operations on Kubernetes resources. For example, to list all pods in a namespace:
namespace = "default"
pods = v1.list_namespaced_pod(namespace)
for pod in pods.items:
    print(f"Pod Name: {pod.metadata.name}")

To create a new pod:

pod_manifest = {
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {"name": "my-pod"},
    "spec": {
        "containers": [
            {
                "name": "my-container",
                "image": "nginx:latest",
            }
        ]
    }
}
v1.create_namespaced_pod(namespace, pod_manifest)

These are just simple examples: the Kubernetes Python client provides methods for creating, updating, deleting, and managing various resources in the cluster.

  1. Exception Handling:
    Be sure to handle exceptions and errors during your interactions with the Kubernetes API. Proper error handling ensures that your scripts gracefully handle unexpected situations.

Using the Kubernetes Python API, you can automate and manage your Kubernetes infrastructure using familiar Python programming paradigms. Consider the official Kubernetes Python client documentation for more in-depth information on available methods, models, and best practices.

Kubernetes Python API Example

Another example script

from kubernetes import client, config

def list_pods(namespace='default'):
    # Load kubeconfig file (optional if running in-cluster)
    # config.load_kube_config()

    # In-cluster configuration (comment out if using kubeconfig)
    config.load_incluster_config()

    # Create an instance of the Kubernetes API client
    v1 = client.CoreV1Api()

    try:
        # List all pods in the specified namespace
        pod_list = v1.list_namespaced_pod(namespace)

        # Print pod details
        print("Pods in namespace {}: ".format(namespace))
        for pod in pod_list.items:
            print(f"{pod.metadata.name} (Status: {pod.status.phase})")

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    # Specify the namespace you want to list pods from
    target_namespace = "your_namespace"

    list_pods(target_namespace)