### Install lightkube Source: https://lightkube.readthedocs.io/en/latest/index Installs the lightkube Python module using pip. Requires Python 3.8 or higher. ```python pip install lightkube ``` -------------------------------- ### Get Deployment Resource using lightkube Client Source: https://lightkube.readthedocs.io/en/latest/resources-and-models Demonstrates how to retrieve a Kubernetes Deployment resource by its name using the lightkube client. It shows the import statements for the Client and Deployment, client instantiation, and the get method call. The output confirms the type of the retrieved object. ```python from lightkube import Client from lightkube.resources.apps_v1 import Deployment client = Client() dep = client.get(Deployment, name="my-deo") type(dep) ``` -------------------------------- ### Instantiate ObjectMeta Model using lightkube Source: https://lightkube.readthedocs.io/en/latest/resources-and-models Shows how to create an instance of the ObjectMeta model from the lightkube library. This model is used for Kubernetes object metadata. The example demonstrates passing 'name' and 'namespace' arguments during instantiation. ```python from lightkube.models.meta_v1 import ObjectMeta ObjectMeta(name='test', namespace='default') ``` -------------------------------- ### Interact with Generic Resources - lightkube Source: https://lightkube.readthedocs.io/en/latest/generic-resources Demonstrates interacting with generic Kubernetes resources using lightkube. It shows how to get a specific resource, access its fields using dictionary notation and attribute access, and create a new resource instance. ```python from lightkube import Client from lightkube.generic_resource import create_namespaced_resource # Define a resource class (e.g., Jobs from the example) Job = create_namespaced_resource('stable.example.com', 'v1', 'Job', 'jobs') client = Client() # Get a specific job resource job = client.get(Job, name="job1", namespace="my-namespace") # Access data using dictionary notation print(job["path"]["to"]["something"]) # Access data using attribute notation print(job.kind) print(job.metadata.name) # Create a new resource instance new_job = Job(metadata={"name": "job2", "namespace": "my-namespace"}, spec={"someKey": "someValue"}) client.create(new_job) # Access subresources like Status job_status = client.get(Job.Status, name="job1", namespace="my-namespace") ``` -------------------------------- ### Render Jinja2 Templates for Kubernetes Resources Source: https://lightkube.readthedocs.io/en/latest/codecs This example illustrates how to use Jinja2 templating to dynamically generate Kubernetes resource configurations. It loads a template file, provides a context for rendering, and then processes the resulting objects. ```python from lightkube import codecs with open('service.tmpl') as f: # render the template using `context` and return the corresponding resource objects. objs = codecs.load_all_yaml(f, context={'env': 'prd'}) print(objs[0].metadata.labels['env']) # prints `prd` ``` -------------------------------- ### Lightkube Label Selector Examples Source: https://lightkube.readthedocs.io/en/latest/selectors Demonstrates various ways to define label selectors in Lightkube for filtering Kubernetes objects based on their labels. Supports equality, inequality, existence, and in/not-in operations. ```python labels={"env": "prod"} ``` ```python labels={"env": "prod", "app": "myapp"} ``` ```python labels={"env": "prod", "app": None} ``` ```python labels={"env": ("prod", "dev")} ``` ```python from lightkube import operators as op ``` ```python labels={"app": op.not_exists()} ``` ```python labels={"env": op.not_equal("prod")} ``` ```python labels={"env": op.not_in(["prod", "dev"])})} ``` -------------------------------- ### Lightkube Field Selector Examples Source: https://lightkube.readthedocs.io/en/latest/selectors Shows how to use field selectors in Lightkube to filter Kubernetes resources based on the values of their fields. Supports equality, inequality, and not-in operations. ```python fields={"metadata.name": "myobj"} ``` ```python fields={"status.phase": "Pending"} ``` ```python fields={"metadata.namespace": op.not_equal("default")}) ``` -------------------------------- ### Client Initialization Source: https://lightkube.readthedocs.io/en/latest/reference/client Initializes a new lightkube client with various configuration options. ```APIDOC ## Client Initialization ### Description Initializes a new lightkube client. The client can be configured with a Kubernetes configuration object, a default namespace, and various other options like timeouts, lazy loading, field managers, environment trust, dry run mode, custom transports, and proxies. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **`config`** (`Union[SingleConfig, KubeConfig, None]`, optional) - Instance of `SingleConfig` or `KubeConfig`. If not set, configuration is detected automatically. - **`namespace`** (`str`, optional) - Default namespace to use for namespaced resources. If not specified, the default namespace from kube configuration is used. - **`timeout`** (`httpx.Timeout`, optional) - Instance of `httpx.Timeout`. Defaults to 10 seconds for all timeouts, read timeout is ignored for watching changes. - **`lazy`** (`bool`, optional) - If set, returned objects are decoded lazily. - **`field_manager`** (`str`, optional) - Name associated with the actor making changes. - **`trust_env`** (`bool`, optional, default: `True`) - Ignore environment variables, passed through to `httpx.Client`. If `False`, an empty config is derived from `DEFAULT_KUBECONFIG`. - **`dry_run`** (`bool`, optional, default: `False`) - Enables server-side dry-run to prevent persistence of modifications. Equivalent to `--dry-run=server` in `kubectl`. - **`transport`** (`httpx.BaseTransport`, optional) - Custom httpx transport. - **`proxy`** (`str`, optional) - HTTP proxy for the httpx client. ### Request Example ```json { "config": null, "namespace": "default", "timeout": null, "lazy": true, "field_manager": null, "trust_env": true, "dry_run": false, "transport": null, "proxy": null } ``` ### Response #### Success Response (200) N/A (This is a constructor) #### Response Example N/A ``` -------------------------------- ### Initialize lightkube Client Source: https://lightkube.readthedocs.io/en/latest/reference/client Creates a new lightkube client instance. Supports configuring connection parameters like namespace, timeouts, and dry-run behavior. The configuration can be automatically detected or provided explicitly. ```python def __init__( self, config: Union[SingleConfig, KubeConfig, None] = None, namespace: str = None, timeout: httpx.Timeout = None, lazy=True, field_manager: str = None, trust_env: bool = True, dry_run: bool = False, transport: httpx.BaseTransport = None, proxy: str = None, ): self._client = GenericSyncClient( config, namespace=namespace, timeout=timeout, lazy=lazy, field_manager=field_manager, trust_env=trust_env, dry_run=dry_run, transport=transport, proxy=proxy, ) ``` -------------------------------- ### List-Watch Pattern Implementation in Python Source: https://lightkube.readthedocs.io/en/latest/list-watch Demonstrates the List-Watch pattern using lightkube. It first lists all Pod objects and then watches for changes starting from the resourceVersion obtained from the list operation. It handles ADDED, MODIFIED, and DELETED events by updating a dictionary of seen pods. The resourceVersion is only available after iteration starts. ```python seen_pods = {} async for pod in (podlist := client.list(Pod)): seen_pods[pod.metadata.name] = pod async for event, pod in client.watch(Pod, resource_version=podlist.resourceVersion): match event: case "ADDED" | "MODIFIED": seen_pods[pod.metadata.name] = pod case "DELETED": del seen_pods[pod.metadata.name] ``` -------------------------------- ### Using Kubernetes Models Source: https://lightkube.readthedocs.io/en/latest/resources-and-models Shows how to import and instantiate Kubernetes model classes, such as ObjectMeta, for creating Kubernetes objects. ```APIDOC ## POST /api/v1/namespaces/{namespace}/{resource_type} ### Description Creates a new Kubernetes object using a model. ### Method POST ### Endpoint `/api/v1/namespaces/{namespace}/{resource_type}` ### Parameters #### Path Parameters - **namespace** (string) - Required - The namespace for the new object. - **resource_type** (string) - Required - The type of resource to create (e.g., 'pods', 'deployments'). #### Request Body - **object** (Object) - Required - The Kubernetes object to create, instantiated from a lightkube model. ### Request Example ```python from lightkube.models.meta_v1 import ObjectMeta from lightkube.resources.core_v1 import Pod # Example using ObjectMeta metadata = ObjectMeta(name='test-pod', namespace='default') # Example of creating a Pod object (simplified) # In a real scenario, you would populate more fields for the Pod spec pod_object = Pod(apiVersion='v1', kind='Pod', metadata=metadata) # Assuming 'client' is an initialized lightkube Client # client.create(pod_object) print(metadata) ``` ### Response #### Success Response (201) - **created_object** (Object) - The newly created Kubernetes object. #### Response Example ```json { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "test-pod", "namespace": "default" } } ``` ``` -------------------------------- ### GET Resource Source: https://lightkube.readthedocs.io/en/latest/reference/client Retrieves a specific Kubernetes resource by name. Raises an ApiError if the resource is not found. ```APIDOC ## GET /api/v1/{resource}/{name} ### Description Retrieves a specific Kubernetes resource by its name. Raises `lightkube.ApiError` if the object does not exist. ### Method GET ### Endpoint /api/v1/{resource}/{name} ### Parameters #### Path Parameters - **res** (Type[GlobalResource | AllNamespacedResource]) - Required - The type of resource to retrieve. - **name** (str) - Required - The name of the resource to fetch. #### Query Parameters - **namespace** (str) - Optional - The name of the namespace containing the resource (for namespaced resources). ### Request Example ```json { "res": "pods", "name": "my-pod", "namespace": "default" } ``` ### Response #### Success Response (200) - **[Resource Object]** - The requested resource object. #### Response Example ```json { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "my-pod", "namespace": "default" }, "spec": { "containers": [ { "name": "nginx", "image": "nginx" } ] } } ``` ``` -------------------------------- ### Scale a Deployment using lightkube Source: https://lightkube.readthedocs.io/en/latest/index Illustrates how to scale a Deployment to a specific number of replicas by replacing its Scale subresource. ```python from lightkube.resources.apps_v1 import Deployment from lightkube.models.meta_v1 import ObjectMeta from lightkube.models.autoscaling_v1 import ScaleSpec obj = Deployment.Scale( metadata=ObjectMeta(name='metrics-server', namespace='kube-system'), spec=ScaleSpec(replicas=1) ) client.replace(obj) ``` -------------------------------- ### Initialize lightkube AsyncClient Source: https://lightkube.readthedocs.io/en/latest/reference/async_client Initializes the AsyncClient for interacting with Kubernetes. It accepts configuration, default namespace, timeouts, and options for lazy decoding, field management, environment trust, dry runs, custom transports, and proxies. Dependencies include 'httpx' for asynchronous operations and 'lightkube' for configuration handling. ```python from typing import Union import httpx from lightkube.core.async_client import GenericAsyncClient from lightkube.config import SingleConfig, KubeConfig def __init__( self, config: Union[SingleConfig, KubeConfig, None] = None, namespace: str = None, timeout: httpx.Timeout = None, lazy=True, field_manager: str = None, trust_env: bool = True, dry_run: bool = False, transport: httpx.AsyncBaseTransport = None, proxy: str = None, ): self._client = GenericAsyncClient( config, namespace=namespace, timeout=timeout, lazy=lazy, field_manager=field_manager, trust_env=trust_env, dry_run=dry_run, transport=transport, proxy=proxy, ) ``` -------------------------------- ### KubeConfig - get Source: https://lightkube.readthedocs.io/en/latest/reference/configuration Retrieves a `SingleConfig` instance based on the provided context name. If no context name is specified, it uses the current context. ```APIDOC ## KubeConfig - get ### Description Returns a `SingleConfig` instance, representing the configuration matching the given `context_name`. Lightkube client will automatically call this method without parameters when an instance of `KubeConfig` is provided. ### Method `get` ### Parameters #### Query Parameters - **context_name** (str) - Optional - Name of the context to use. If `context_name` is undefined, the `current-context` is used. In the case both contexts are undefined, and the default is provided, this method will return the default. It will fail with an error otherwise. - **default** (SingleConfig) - Optional - Instance of a `SingleConfig` to be returned in case both contexts are not set. When this parameter is not provided and no context is defined, the method call will fail. ### Request Example ```json { "context_name": "my-cluster-context" } ``` ### Response #### Success Response (200) - **SingleConfig** (object) - A `SingleConfig` object containing the Kubernetes configuration for the specified context. #### Response Example ```json { "context_name": "my-cluster-context", "context": { "cluster": "kubernetes", "user": "kubernetes-admin", "namespace": "default" }, "cluster": { "server": "https://192.168.1.100:6443", "certificate_authority_data": "..." }, "user": { "token": "..." }, "namespace": "default" } ``` ``` -------------------------------- ### Create a ConfigMap using lightkube Source: https://lightkube.readthedocs.io/en/latest/index Illustrates the creation of a ConfigMap resource with specified metadata and data. The ConfigMap is then created in the Kubernetes cluster. ```python from lightkube.resources.core_v1 import ConfigMap from lightkube.models.meta_v1 import ObjectMeta config = ConfigMap( metadata=ObjectMeta(name='my-config', namespace='default'), data={'key1': 'value1', 'key2': 'value2'} ) client.create(config) ``` -------------------------------- ### Get Generic Resource Source: https://lightkube.readthedocs.io/en/latest/generic-resources Query generic resources by their version and kind. This allows you to retrieve definitions for custom resources or other generic types. ```APIDOC ## GET /generic_resource ### Description Query generic resources already defined using one of the other methods described in this module or via `codecs.load_all_yaml(..., create_resources_for_crds=True)` ### Method GET ### Endpoint /generic_resource ### Parameters #### Query Parameters - **version** (str) - Required - Resource version including the API group. Example `stable.example.com/v1` - **kind** (str) - Required - Resource kind. Example: `CronTab` ### Response #### Success Response (200) - **resource** (class) - A class representing the generic resource or None if it's not found. #### Response Example ```json { "resource": "CronTab" } ``` ``` -------------------------------- ### Update deployment status asynchronously Source: https://lightkube.readthedocs.io/en/latest/async-usage Updates the status of a deployment asynchronously using the AsyncClient. This example shows how to set the 'observedGeneration' in the DeploymentStatus. ```python from lightkube import AsyncClient from lightkube.resources.apps_v1 import Deployment from lightkube.models.apps_v1 import DeploymentStatus async def example(): client = AsyncClient() obj = Deployment.Status( status=DeploymentStatus(observedGeneration=99) ) await client.apply(obj, name='metrics-server', namespace='kube-system') ``` -------------------------------- ### GET /apis/apps/v1/{namespace}/{resource}/{name} Source: https://lightkube.readthedocs.io/en/latest/reference/async_client Retrieves a specific Kubernetes object by its name and optionally namespace. Raises an ApiError if the object is not found. ```APIDOC ## GET /apis/apps/v1/{namespace}/{resource}/{name} ### Description Retrieves a specific Kubernetes object by its name. Raises `lightkube.ApiError` if the object does not exist. ### Method GET ### Endpoint /apis/apps/v1/{namespace}/{resource}/{name} ### Parameters #### Path Parameters - **res** (Type[Resource]) - Required - The resource kind to retrieve. - **name** (str) - Required - The name of the object to fetch. - **namespace** (str) - Optional - The namespace of the object. Required for namespaced resources, ignored for global resources. ### Request Example ```json { "res": "Pods", "name": "my-pod", "namespace": "default" } ``` ### Response #### Success Response (200) - **[Resource Object]** - The retrieved Kubernetes object. #### Response Example ```json { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "my-pod", "namespace": "default" }, "spec": { ... }, "status": { ... } } ``` ``` -------------------------------- ### Create Resources from YAML file using lightkube Source: https://lightkube.readthedocs.io/en/latest/index Demonstrates reading multiple Kubernetes resource definitions from a YAML file and creating them using the lightkube client. ```python from lightkube import Client, codecs client = Client() with open('deployment.yaml') as f: for obj in codecs.load_all_yaml(f): client.create(obj) ``` -------------------------------- ### Read a pod asynchronously Source: https://lightkube.readthedocs.io/en/latest/async-usage Retrieves a specific pod by its name and namespace using the AsyncClient. It demonstrates how to use 'await' with the 'get' operation and access pod details. ```python from lightkube import AsyncClient from lightkube.resources.core_v1 import Pod async def example(): client = AsyncClient() pod = await client.get(Pod, name="my-pod", namespace="default") print(pod.namespace.uid) ``` -------------------------------- ### Load Kubernetes Configuration from File (Python) Source: https://lightkube.readthedocs.io/en/latest/configuration Loads Kubernetes connection configuration from a specified kubeconfig file. It demonstrates how to initialize a lightkube Client using this configuration, optionally selecting a specific context. ```Python from lightkube import KubeConfig, Client config = KubeConfig.from_file("path/to/my/config") client = Client(config=config) ``` ```Python # pick the current context from lightkube import KubeConfig, Client config = KubeConfig.from_file("path/to/my/config") client = Client(config=config.get()) ``` ```Python # use the context named my-context client = Client(config=config.get(context_name='my-context')) ``` -------------------------------- ### AsyncClient Initialization Source: https://lightkube.readthedocs.io/en/latest/reference/async_client Initializes a new Lightkube client for asynchronous operations. Allows configuration of connection, namespace, timeouts, and other client behaviors. ```APIDOC ## AsyncClient ### Description Initializes a new lightkube client for asynchronous operations. This client allows for interaction with Kubernetes resources asynchronously. ### Method __init__ ### Endpoint N/A (This is a class constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **`config`** (`Union[SingleConfig, KubeConfig, None]`, default: `None`) Instance of `SingleConfig` or `KubeConfig`. When not set, the configuration will be detected automatically using the following order: in-cluster config, `KUBECONFIG` environment variable, `~/.kube/config` file. * **`namespace`** (`str`, default: `None`) Default namespace to use. This attribute is used in case namespaced resources are called without defining a namespace. If not specified, the default namespace set in your kube configuration will be used. * **`timeout`** (`httpx.Timeout`, default: `None`) Instance of `httpx.Timeout`. By default, all timeouts are set to 10 seconds. Notice that the read timeout is ignored when watching changes. * **`lazy`** (`bool`, default: `True`) When set, the returned objects will be decoded from the JSON payload in a lazy way, i.e., only when accessed. * **`field_manager`** (`str`, default: `None`) Name associated with the actor or entity that is making these changes. * **`trust_env`** (`bool`, default: `True`) Ignore environment variables, also passed through to httpx.AsyncClient trust_env. See its docs for further description. If False, empty config will be derived from_file(DEFAULT_KUBECONFIG). * **`dry_run`** (`bool`, default: `False`) Apply server-side dry-run and guarantee that modifications will not be persisted in storage. Setting this field to `True` is equivalent of passing `--dry-run=server` to `kubectl` commands. * **`transport`** (`httpx.AsyncBaseTransport`, default: `None`) Custom httpx transport. * **`proxy`** (`str`, default: `None`) HTTP proxy for the httpx client. ### Request Example ```json { "config": null, "namespace": "default", "timeout": null, "lazy": true, "field_manager": null, "trust_env": true, "dry_run": false, "transport": null, "proxy": null } ``` ### Response #### Success Response (200) N/A (This is a constructor, it does not return a value in the traditional sense but initializes the object.) #### Response Example N/A ``` -------------------------------- ### GET /api/v1/namespaces/{namespace}/pods/{name}/log Source: https://lightkube.readthedocs.io/en/latest/reference/async_client Retrieves log lines for a specified Kubernetes pod. Supports streaming, time-based filtering, and custom output formatting. ```APIDOC ## GET /api/v1/namespaces/{namespace}/pods/{name}/log ### Description Retrieves log lines for a specified Kubernetes pod. This endpoint allows for streaming logs, filtering by time, and controlling output formatting. ### Method GET ### Endpoint /api/v1/namespaces/{namespace}/pods/{name}/log ### Parameters #### Path Parameters - **name** (str) - Required - Name of the Pod. - **namespace** (str) - Optional - Name of the namespace containing the Pod. #### Query Parameters - **container** (str) - Optional - The container for which to stream logs. Defaults to the only container if the pod has just one. - **follow** (bool) - Optional - If `True`, follow the log stream of the pod. - **since** (int) - Optional - If set, fetch logs from a relative time in seconds before the current time. - **tail_lines** (int) - Optional - If set, fetch the specified number of lines from the end of the logs. - **timestamps** (bool) - Optional - If `True`, add a timestamp to the beginning of every log line. - **newlines** (bool) - Optional - If `True`, each line will end with a newline; otherwise, newlines are stripped. ### Request Example ```json { "name": "my-pod", "namespace": "default", "container": "my-app", "follow": true, "since": 3600, "tail_lines": 100, "timestamps": true, "newlines": true } ``` ### Response #### Success Response (200) - **log_lines** (AsyncIterable[str]) - An asynchronous iterable yielding log lines. ``` -------------------------------- ### Accessing Kubernetes Resources Source: https://lightkube.readthedocs.io/en/latest/resources-and-models Demonstrates how to import and use resource classes from lightkube to interact with the Kubernetes API, specifically retrieving a Deployment. ```APIDOC ## GET /api/v1/namespaces/{namespace}/deployments/{name} ### Description Retrieves a specific Deployment resource from the Kubernetes API. ### Method GET ### Endpoint `/api/v1/namespaces/{namespace}/deployments/{name}` ### Parameters #### Path Parameters - **namespace** (string) - Required - The namespace of the deployment. - **name** (string) - Required - The name of the deployment. ### Request Example ```python from lightkube import Client from lightkube.resources.apps_v1 import Deployment client = Client() dep = client.get(Deployment, name="my-deployment", namespace="default") print(type(dep)) ``` ### Response #### Success Response (200) - **deployment** (Deployment) - The Deployment object if found. #### Response Example ```json { "apiVersion": "apps/v1", "kind": "Deployment", "metadata": { "name": "my-deployment", "namespace": "default" }, "spec": { "replicas": 1 } } ``` ``` -------------------------------- ### Get Kubernetes Resource by Name (Async) Source: https://lightkube.readthedocs.io/en/latest/reference/async_client Asynchronously retrieves a Kubernetes resource by its name. Supports both global and namespaced resources. Raises lightkube.ApiError if the specified resource does not exist. ```python async def get(self, res, name, *, namespace=None): """Return an object. Raise `lightkube.ApiError` if the object doesn't exist. Parameters: res: Resource kind. name: Name of the object to fetch. namespace: Name of the namespace containing the object (Only for namespaced resources). """ return await self._client.request( "get", res=res, name=name, namespace=namespace ) ``` -------------------------------- ### Create KubeConfig from dictionary Source: https://lightkube.readthedocs.io/en/latest/reference/configuration Shows how to create a KubeConfig instance from a dictionary representation of the configuration. This class method parses the dictionary, extracting clusters, contexts, and users, and resolves relative paths using the provided filename. ```python @classmethod def from_dict(cls, conf: Dict, fname=None): """Creates a KubeConfig instance from the content of a dictionary structure. **Parameters** * **conf**: Configuration structure, main attributes are `clusters`, `contexts`, `users` and `current-context`. * **fname**: File path from where this configuration has been loaded. This is needed to resolve relative paths present inside the configuration. """ return cls( current_context=conf.get("current-context"), clusters=to_mapping(conf["clusters"], "cluster", factory=Cluster), contexts=to_mapping(conf["contexts"], "context", factory=Context), users=to_mapping(conf.get("users", []), "user", factory=User), fname=fname, ) ``` -------------------------------- ### Get Resource by Name and Namespace with lightkube Source: https://lightkube.readthedocs.io/en/latest/reference/client Retrieves a specific Kubernetes resource by its name and optionally namespace. If the resource is not found, it raises a `lightkube.ApiError`. This function is crucial for fetching detailed information about individual objects. ```python def get(self, res, name, *, namespace=None): """Return an object. Raise `lightkube.ApiError` if the object doesn't exist. Parameters: res: Resource kind. name: Name of the object to fetch. namespace: Name of the namespace containing the object (Only for namespaced resources). """ return self._client.request("get", res=res, name=name, namespace=namespace) ``` -------------------------------- ### GET /api/v1/namespaces/{namespace}/pods/{name}/log Source: https://lightkube.readthedocs.io/en/latest/reference/client Retrieves log lines for a specified Kubernetes Pod. Supports streaming logs, filtering by time, and controlling output formatting. Raises an ApiError if the Pod is not found. ```APIDOC ## GET /api/v1/namespaces/{namespace}/pods/{name}/log ### Description Retrieves log lines for a specified Kubernetes Pod. Supports streaming logs, filtering by time, and controlling output formatting. Raises an ApiError if the Pod is not found. ### Method GET ### Endpoint /api/v1/namespaces/{namespace}/pods/{name}/log ### Parameters #### Path Parameters - **name** (str) - Required - The name of the Pod. - **namespace** (str) - Optional - The namespace containing the Pod. #### Query Parameters - **container** (str) - Optional - The container within the Pod to stream logs from. Defaults to the only container if the Pod has just one. - **follow** (bool) - Optional - If True, the log stream will be followed. - **since** (int) - Optional - Fetch logs from a relative time in seconds before the current time. - **tail_lines** (int) - Optional - Fetch the last N lines from the logs. - **timestamps** (bool) - Optional - If True, add a timestamp to each log line. - **newlines** (bool) - Optional - If True, ensure each log line ends with a newline character; otherwise, newlines are stripped. ### Request Example ```json { "name": "my-pod", "namespace": "default", "container": "my-app-container", "follow": false, "since": 3600, "tail_lines": 100, "timestamps": true, "newlines": true } ``` ### Response #### Success Response (200) - **log_lines** (Iterator[str]) - An iterator yielding log lines from the Pod. #### Response Example ``` 2023-10-27T10:00:00Z This is the first log line. 2023-10-27T10:00:01Z This is the second log line. ``` ``` -------------------------------- ### Initialize KubeConfig manually Source: https://lightkube.readthedocs.io/en/latest/reference/configuration Demonstrates the manual initialization of the KubeConfig class. This method is typically not called directly but through specific constructors. It takes dictionaries for clusters, contexts, and optionally users, along with the current context and filename. ```python def __init__( self, *, clusters, contexts, users=None, current_context=None, fname=None ): """ Create the kubernetes configuration manually. Normally this constructor should not be called directly. Use a specific constructor instead. Attributes: clusters: Dictionary of cluster name -> `Cluster` instance. contexts: Dictionary of context name -> `Context` instance. users: Dictionary of user name -> `User` instance. current_context: Name of the current context. fname: Name of the file where the configuration has been readed from. """ self.current_context = current_context self.clusters = clusters self.contexts = contexts self.users = users or {} self.fname = Path(fname) if fname else None ``` -------------------------------- ### Create Configuration from Server URL Source: https://lightkube.readthedocs.io/en/latest/reference/configuration Creates an instance of the KubeConfig class directly from a cluster server URL. ```APIDOC ## classmethod from_server ### Description Creates an instance of the KubeConfig class from the cluster server url. ### Method classmethod ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL of the Kubernetes API server. - **namespace** (string) - Optional - Default namespace for the context. ### Request Example None ### Response #### Success Response (200) KubeConfig object #### Response Example None ``` -------------------------------- ### Apply Kubernetes Resource Asynchronously (Python) Source: https://lightkube.readthedocs.io/en/latest/reference/async_client The `apply` method creates or configures a Kubernetes object using server-side apply. It supports both global and namespaced resources, and allows for optional parameters like `field_manager`, `force`, and `dry_run`. If `namespace` or `name` are not provided, they are inferred from the object's metadata. ```Python async def apply( self, obj, name=None, *, namespace=None, field_manager=None, force=False, dry_run: bool = False, ): """Create or configure an object. This method uses the [server-side apply](https://kubernetes.io/docs/reference/using-api/server-side-apply/) functionality. Parameters: obj: object to create. This need to be an instance of a resource kind. name: Required only for sub-resources: Name of the resource to which this object belongs. namespace: Name of the namespace containing the object (Only for namespaced resources). If the namespace doesn't exist, `lightkube.ApiError` is raised. field_manager: Name associated with the actor or entity that is making these changes. force: Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. dry_run: Apply server-side dry-run and guarantee that modifications will not be persisted in storage. Setting this field to `True` is equivalent of passing `--dry-run=server` to `kubectl` commands. """ if ( namespace is None and isinstance(obj, r.NamespacedResource) and obj.metadata.namespace ): namespace = obj.metadata.namespace if name is None and obj.metadata.name: name = obj.metadata.name return await self.patch( type(obj), name, obj, namespace=namespace, patch_type=PatchType.APPLY, field_manager=field_manager, force=force, dry_run=dry_run, ) ``` -------------------------------- ### Watch Deployments using lightkube Source: https://lightkube.readthedocs.io/en/latest/index Demonstrates how to watch for changes in Deployment resources within a specified namespace. It prints the namespace and replica count for each update. ```python from lightkube import Client from lightkube.resources.apps_v1 import Deployment client = Client() for op, dep in client.watch(Deployment, namespace="default"): print(f"{dep.namespace.name} {dep.spec.replicas}") ``` -------------------------------- ### Get Specific KubeConfig Context (Python) Source: https://lightkube.readthedocs.io/en/latest/reference/configuration Retrieves a SingleConfig instance for a specified context name. If no context name is provided, it defaults to the current context. An optional default SingleConfig can be provided if no context is set. It handles KeyErrors for missing contexts and ConfigErrors for undefined contexts without a default. ```python def get( self, context_name=None, default: SingleConfig = None ) -> Optional[SingleConfig]: """Returns a `SingleConfig` instance, representing the configuration matching the given `context_name`. Lightkube client will automatically call this method without parameters when an instance of `KubeConfig` is provided. **Parameters** * **context_name**: Name of the context to use. If `context_name` is undefined, the `current-context` is used. In the case both contexts are undefined, and the default is provided, this method will return the default. It will fail with an error otherwise. * **default**: Instance of a `SingleConfig` to be returned in case both contexts are not set. When this parameter is not provided and no context is defined, the method call will fail. """ if context_name is None: context_name = self.current_context if context_name is None: if default is None: raise exceptions.ConfigError( "No current context set and no default provided" ) return default try: ctx = self.contexts[context_name] except KeyError: raise exceptions.ConfigError(f"Context '{context_name}' not found") return SingleConfig( context_name=context_name, context=ctx, cluster=self.clusters[ctx.cluster], user=self.users[ctx.user] if ctx.user else None, fname=self.fname, ) ``` -------------------------------- ### Async Create Kubernetes Object (Python) Source: https://lightkube.readthedocs.io/en/latest/reference/async_client Asynchronously creates a Kubernetes object using the provided parameters. Supports global and namespaced resources, with options for specifying name, namespace, field manager, and dry-run. ```python async def create( self, obj, name=None, *, namespace=None, field_manager=None, dry_run: bool = False, ): """Create a new object and return its representation. Raise `lightkube.ApiError` if the object already exist. Parameters: obj: object to create. This need to be an instance of a resource kind. name: Required only for sub-resources: Name of the resource to which this object belongs. namespace: Name of the namespace containing the object (Only for namespaced resources). If the namespace doesn't exist, `lightkube.ApiError` is raised. field_manager: Name associated with the actor or entity that is making these changes. This parameter overrides the corresponding `Client` initialization parameter. dry_run: Apply server-side dry-run and guarantee that modifications will not be persisted in storage. Setting this field to `True` is equivalent of passing `--dry-run=server` to `kubectl` commands. """ return await self._client.request( "post", name=name, namespace=namespace, obj=obj, params={ "fieldManager": field_manager, "dryRun": "All" if dry_run else None, }, ) ``` -------------------------------- ### Server-Side Apply with lightkube Source: https://lightkube.readthedocs.io/en/latest/index Demonstrates using server-side apply to create and modify Kubernetes resources. It requires specifying a `field_manager` and includes `apiVersion` and `kind` in the object definition. ```python from lightkube.resources.core_v1 import ConfigMap from lightkube.models.meta_v1 import ObjectMeta client = Client(field_manager="my-manager") config = ConfigMap( # note apiVersion and kind need to be specified for server-side apply apiVersion='v1', kind='ConfigMap', metadata=ObjectMeta(name='my-config', namespace='default'), data={'key1': 'value1', 'key2': 'value2'} ) res = client.apply(config) print(res.data) # prints {'key1': 'value1', 'key2': 'value2'} del config.data['key1'] config.data['key3'] = 'value3' res = client.apply(config) print(res.data) # prints {'key2': 'value2', 'key3': 'value3'} ``` -------------------------------- ### Load Configuration from File Source: https://lightkube.readthedocs.io/en/latest/reference/configuration Creates an instance of the KubeConfig class from a kubeconfig file in YAML format. ```APIDOC ## classmethod from_file ### Description Creates an instance of the KubeConfig class from a kubeconfig file in YAML format. ### Method classmethod ### Parameters #### Path Parameters - **fname** (string) - Required - Path to the kuberneted configuration. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) KubeConfig object #### Response Example None ``` -------------------------------- ### Create Kubernetes Config from File (Python) Source: https://lightkube.readthedocs.io/en/latest/reference/configuration Creates a KubeConfig instance from a YAML-formatted kubeconfig file. It validates the file's existence before parsing. Dependencies include 'Path' for file path manipulation, 'yaml' for parsing, and 'lightkube' for configuration and exception handling. ```Python from lightkube.config import KubeConfig from pathlib import Path import yaml # Example usage: # config = KubeConfig.from_file('~/.kube/config') # print(config) ``` -------------------------------- ### Create Kubernetes Resources from YAML Source: https://lightkube.readthedocs.io/en/latest/codecs This snippet demonstrates how to create Kubernetes resources defined in a YAML file using the lightkube client. It iterates through all YAML documents in the file and creates each resource. ```python from lightkube import Client, codecs client = Client() with open('deployment.yaml') as f: for obj in codecs.load_all_yaml(f): client.create(obj) ``` -------------------------------- ### POST /create Source: https://lightkube.readthedocs.io/en/latest/reference/client Creates a new Kubernetes object on the cluster. This method supports both global and namespaced resources, as well as sub-resources. It returns the created object or raises an ApiError if the object already exists. ```APIDOC ## POST /create ### Description Creates a new Kubernetes object and returns its representation. Raises `lightkube.ApiError` if the object already exists. ### Method POST ### Endpoint This method is part of the client object and does not have a direct HTTP endpoint in the traditional sense. The actual endpoint depends on the type of resource being created. ### Parameters #### Path Parameters None #### Query Parameters - **field_manager** (str) - Optional - Name associated with the actor or entity that is making these changes. This parameter overrides the corresponding `Client` initialization parameter. - **dry_run** (bool) - Optional - Apply server-side dry-run and guarantee that modifications will not be persisted in storage. Equivalent to `--dry-run=server`. #### Request Body - **obj** (Resource) - Required - The Kubernetes resource object to create. Must be an instance of a resource kind. - **name** (str) - Optional - Required only for sub-resources: Name of the resource to which this object belongs. - **namespace** (str) - Optional - Name of the namespace containing the object (Only for namespaced resources). If the namespace doesn't exist, `lightkube.ApiError` is raised. ### Request Example ```json { "obj": "", "name": "my-resource", "namespace": "default", "field_manager": "my-app", "dry_run": false } ``` ### Response #### Success Response (200 or 201) - **** (object) - The created Kubernetes resource object. #### Response Example ```json { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "my-pod" }, "spec": { "containers": [ { "name": "nginx", "image": "nginx" } ] } } ``` ```