Skip to main content

Create Kubernetes CRD using Python dataclasses

Project description

Kube CRDs

The primary purpose of this project is to simplify working with Kubernetes Custom Resources. To achieve that it provides a base class, kubecrds.KubeResourceBase that can create Python dataclassses into Kubernetes Custom Resources and also generate and install Custom Resource Definitions for those resource into the K8s cluster directly.


✅ Supported Versions

This project actively supports non-EOL (actively maintained) versions of both Python and Kubernetes to ensure long-term compatibility and stability.

  • Python: 3.11 · 3.12 · 3.13 · 3.14 Only actively supported Python releases are tested and guaranteed to work.

  • Kubernetes: 1.31.x · 1.32.x · 1.33.x · 1.34.x Each supported Kubernetes release aligns with currently active upstream versions, verified through automated Kind-based test environments.

🧩 Our CI pipeline automatically runs tests against multiple Python and Kubernetes versions to prevent regressions and maintain backward compatibility across all active releases.


Example

from dataclasses import dataclass, field
from uuid import UUID
from kubecrds import KubeResourceBase
from apischema import schema

@dataclass
class Resource(KubeResourceBase):
     __group__ = 'example.com'
     __version__ = 'v1alpha1'

     name: str
     tags: list[str] = field(
         default_factory=list,
         metadata={
            description='regroup multiple resources',
            unique=False,
         },
     )

print(Resource.crd_schema())

YAML Manifest

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: resources.example.com
spec:
  group: example.com
  names:
    kind: Resource
    plural: resources
    singular: resource
  scope: Namespaced
  versions:
  - name: v1alpha1
    schema:
      openAPIV3Schema:
        properties:
          spec:
            properties:
              name:
                type: string
              tags:
                default: []
                description: regroup multiple resources
                items:
                  type: string
                type: array
                uniqueItems: false
            required:
            - name
            type: object
        type: object
    served: true
    storage: true

Create CRD in K8s Cluster

It is also possible to install the CRD in a cluster using a Kubernetes Client object::

from kubernetes import client, config
config.load_kube_config()
k8s_client = client.ApiClient()
Resource.install(k8s_client)

You can then find the resource in the cluster:

kubectl get crds/resources.example.com

Output:

NAME                    CREATED AT
resources.example.com   2022-03-20T03:58:25Z

Grep your resources

kubectl api-resources | grep example.com

Output:

resources     example.com/v1alpha1                  true         Resource

Installation of resource is idempotent, so re-installing an already installed resource doesn't raise any exceptions if exist_ok=True is passed in::

Resource.install(k8s_client, exist_ok=True)

Serialization

You can serialize a Resource such that it is suitable to POST to K8s::

example = Resource(name='myResource', tags=['tag1', 'tag2'])
import json
print(json.dumps(example.serialize(), sort_keys=True, indent=4))

Output:

{
    "apiVersion": "example.com/v1alpha1",
    "kind": "Resource",
    "metadata": {
        "name": "..."
    },
    "spec": {
        "name": "myResource",
        "tags": [
            "tag1",
            "tag2"
        ]
    }
}

Objects can also be serialized and saved directly in K8s::

example.save(k8s_client)

Where client in the above is a Kubernetes client object. You can also use asyncio with kubernetes_asyncio client and instead do::

await example.async_save(k8s_async_client)

Deserialization

You can deserialize the JSON from Kubernetes API into Python CR objects. ::

cat -p testdata/cr.json
{
  "apiVersion": "example.com/v1alpha1",
  "kind": "Resource",
  "metadata": {
      "generation": 1,
      "name": "myresource1",
      "namespace": "default",
      "resourceVersion": "105572812",
      "uid": "02102eb3-968b-418a-8023-75df383daa3c"
  },
  "spec": {
      "name": "bestID",
      "tags": [
          "tag1",
          "tag2"
      ]
  }
}

by using from_json classmethod on the resource::

import json
with open('testdata/cr.json') as fd:
  json_schema = json.load(fd)

res = Resource.from_json(json_schema)

print(res.name)
# bestID

print(res.tags)
# ['tag1', 'tag2']

This also loads the Kubernetes's V1ObjectMeta and sets it as the .metadata property of CR::

print(res.metadata.namespace)
# default

print(res.metadata.name)
# myresource1

print(res.metadata.resource_version)
# 105572812

Watch

It is possible to Watch for changes in Custom Resources using the standard Watch API in Kubernetes. For example, to watch for all changes in Resources:

async for happened, resource in Resource.async_watch(k8s_async_client):
  print(f'Resource {resource.metadata.name} was {happened}')

Or you can use the block sync API for the watch::

for happened, resource in Resource.watch(k8s_client):
  print(f'Resource {resource.metadata.name} was {happened}')

Installing

Kube CRD can be install from PyPI using pip or your favorite tool::

pip install kubecrds

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

kubecrds-34.1.3.tar.gz (10.1 kB view details)

Uploaded Source

Built Distribution

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

kubecrds-34.1.3-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

Details for the file kubecrds-34.1.3.tar.gz.

File metadata

  • Download URL: kubecrds-34.1.3.tar.gz
  • Upload date:
  • Size: 10.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.3 Linux/6.11.0-1018-azure

File hashes

Hashes for kubecrds-34.1.3.tar.gz
Algorithm Hash digest
SHA256 02d7aecac5eda3c2de6a34f5afcd65c437b8386489075bfff9006ec0aabec026
MD5 8748cfb975f17ff4972fcc92a9b0169f
BLAKE2b-256 76f8f05983a0f3de7a4ff1597f3ebbacb6ac611d0b7bb7a34614dd33fb862d9f

See more details on using hashes here.

File details

Details for the file kubecrds-34.1.3-py3-none-any.whl.

File metadata

  • Download URL: kubecrds-34.1.3-py3-none-any.whl
  • Upload date:
  • Size: 11.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.3 Linux/6.11.0-1018-azure

File hashes

Hashes for kubecrds-34.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 698ea1aa0fcf89853e62de8ee287ea9f3f45e14cce69b5af3bdbfa6b724402e7
MD5 0a0e6debdd9c29c0817460e967d380aa
BLAKE2b-256 c16a9523517db5534f0149afd36c8c7087f8aba3b26bd40e0e83d35c193b372d

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