Skip to main content

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 msgspec Structs for fast, allocation-efficient serialisation.
  • Load/Dump resource objects from YAML.
  • Support for async/await
  • Support for installing a specific version of the kubernetes models (1.21 to 1.36)
  • 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 httpx2.

Installation

This module requires python >= 3.10

pip install lightkube

Usage

List

Read a pod

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

with Client() as 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.

Release files for lightkube 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lightkube 1.0.0
File Size Uploaded
lightkube-1.0.0.tar.gz 38.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for lightkube 1.0.0
File Interpreter ABI Platform
lightkube-1.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 87.9 kB

Release files / lightkube-1.0.0.tar.gz

Download URL lightkube-1.0.0.tar.gz
Size 38.7 kB
Tags Source
SHA-256 checksum
How to use checksums
28fcdb3acce2ffcd3fa6b149cdf43186a4a6a9ce1c43c0e3c6bbc4575c478570
BLAKE2b-256 checksum
How to use checksums
a908a390b621fb698f91b118bb473d9f58aac15a83427c8a2d049dcc88b845e7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.3

Release files / lightkube-1.0.0-py3-none-any.whl

Download URL lightkube-1.0.0-py3-none-any.whl
Size 49.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
614d85324846f2a9af4628bc0ec2825617aa402eeacdb3a2b1331581e52f49b5
BLAKE2b-256 checksum
How to use checksums
31938e1c6fffc18f74cdf7590c23b6e340ae8d920832413577d57978df780ae4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.3

Release history Release notifications | RSS feed

1.0.1

2 release files

This release

1.0.0 This release

2 release files

0.21.0

2 release files

0.19.0

2 release files

0.18.0

2 release files

0.17.2

2 release files

0.16.2

2 release files

0.16.1

2 release files

0.16.0

2 release files

0.15.8

2 release files

0.15.7

2 release files

0.15.4

2 release files

0.15.3

2 release files

0.15.2

2 release files

0.15.0

2 release files

0.14.0

2 release files

0.13.0

2 release files

0.12.0

2 release files

0.11.0

2 release files

0.10.2

2 release files

0.10.1

2 release files

0.10.0

2 release files

0.9.0

2 release files

0.8.1

2 release files

0.8.0

1 release file

0.7.2

1 release file

0.7.1

1 release file

0.6.0

1 release file

0.5.1

1 release file

0.4.1

1 release file

0.2.1

1 release file

0.2.0

1 release file

0.0.1

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page