Skip to main content

Lightweight kubernetes client library

Project description

lightkube

Coverage Status pypi supported versions

Modern lightweight kubernetes module for python

Highlights

  • Simple interface shared across all kubernetes APIs.
  • Extensive type hints to avoid common mistakes and to support autocompletion.
  • Models and resources generated from the swagger specifications using standard dataclasses.
  • Load/Dump resource objects from YAML.
  • Support for async/await
  • Support for installing a specific version of the kubernetes models (1.20 to 1.35)
  • Lazy instantiation of inner models.
  • Fast startup and small memory footprint as only needed models and resources can be imported.
  • Automatic handling of pagination when listing resources.

This module is powered by httpx.

Installation

This module requires python >= 3.8

pip install lightkube

Usage

List

Read a pod

from lightkube import Client
from lightkube.resources.core_v1 import Pod

client = Client()
pod = client.get(Pod, name="my-pod", namespace="default")
print(pod.namespace.uid)

List nodes

from lightkube import Client
from lightkube.resources.core_v1 import Node

client = Client()
for node in client.list(Node):
    print(node.metadata.name)

Create

Create a config map

from lightkube import Client
from lightkube.resources.core_v1 import ConfigMap
from lightkube.models.meta_v1 import ObjectMeta

client = Client()
config = ConfigMap(
    metadata=ObjectMeta(name='my-config', namespace='default'),
    data={'key1': 'value1', 'key2': 'value2'}
)

client.create(config)

Create resources defined in a file

from lightkube import Client, codecs

client = Client()
with open('deployment.yaml') as f:
    for obj in codecs.load_all_yaml(f):
        client.create(obj)

Modify

Replace the previous config with a different content

config.data['key1'] = 'new value'
client.replace(config)

Patch an existing config adding more data

patch = {"data": {"key3": "value3"}}
client.patch(ConfigMap, name="my-config", obj=patch)

Remove the just added data key key3

# When using PatchType.MERGE, setting a value of a key/value to None, will remove the current item 
patch = {'metadata': {"key3": None}}
client.patch(ConfigMap, name='my-config', namespace='default', obj=patch, patch_type=PatchType.MERGE)

Add a label

client.set(ConfigMap, name="my-config", labels={'env': 'prod'})

Remove a label

client.set(ConfigMap, name="my-config", labels={'env': None})

Scale a deployment

from lightkube import Client
from lightkube.resources.apps_v1 import Deployment
from lightkube.models.meta_v1 import ObjectMeta
from lightkube.models.autoscaling_v1 import ScaleSpec

client = Client()
obj = Deployment.Scale(
    metadata=ObjectMeta(name='metrics-server', namespace='kube-system'),
    spec=ScaleSpec(replicas=1)
)
client.replace(obj)

Update Status of a deployment

from lightkube import Client
from lightkube.resources.apps_v1 import Deployment
from lightkube.models.apps_v1 import DeploymentStatus

client = Client()
obj = Deployment.Status(
    status=DeploymentStatus(observedGeneration=99)
)
client.apply(obj, name='metrics-server', namespace='kube-system')

Create and modify resources using server side apply

Note: field_manager is required for server-side apply. You can specify it once in the client constructor or when calling apply(). Also apiVersion and kind need to be provided as part of the object definition.

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'}

Delete

Delete a namespaced resource

client.delete(ConfigMap, name='my-config', namespace='default')

Monitoring & Interaction

Watch deployments

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}")

Stream pod logs

from lightkube import Client

client = Client()
for line in client.log('my-pod', follow=True):
    print(line)

Execute a command inside a pod

from lightkube import Client

client = Client()

# Capture stdout or raise ApiError if error code is != 0
res = client.exec('my-pod', namespace='default', container='main', command=['ls', '-l', '/'], 
    stdout=True, raise_on_error=True)
print(res.stdout)

# Send data to stdin and capture output
res = client.exec('my-pod', namespace='default', container='main', command=['cat'], 
    stdin='hello\n', stdout=True)
print(res.stdout)
print(res.exit_code)

Unsupported features

The following features are not supported at the moment:

  • Special subresources attach, portforward and proxy.
  • auth-provider authentication method is not supported. The supported authentication methods are token, tokenFile, username + password and exec.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

lightkube-0.21.0.tar.gz (36.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

lightkube-0.21.0-py3-none-any.whl (47.2 kB view details)

Uploaded Python 3

File details

Details for the file lightkube-0.21.0.tar.gz.

File metadata

  • Download URL: lightkube-0.21.0.tar.gz
  • Upload date:
  • Size: 36.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for lightkube-0.21.0.tar.gz
Algorithm Hash digest
SHA256 720910200de4bd88e0d7b5d2edfb45a4f6be292798b8776d7b551ef5a5ccdc15
MD5 f826d2af441a399480a9ebdfed066c21
BLAKE2b-256 e7e09329c34cab5fb5738ea54c2af1952f32f5ecedbed03779d1b82eb329ba8a

See more details on using hashes here.

File details

Details for the file lightkube-0.21.0-py3-none-any.whl.

File metadata

  • Download URL: lightkube-0.21.0-py3-none-any.whl
  • Upload date:
  • Size: 47.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for lightkube-0.21.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5218c9a7029b5ba8a3e90534141795c6bb3ec3e96894afccb55f0581ca8d59b2
MD5 a650d007aadf40ec1f770e8801e90936
BLAKE2b-256 32b7e22e80fa11d82b03cc6329993e577aecf9bc781306a121f2d11f910d3aec

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page