跳转到主要内容

使用Python数据类创建Kubernetes CRD

项目描述

此项目的首要目的是简化使用Kubernetes自定义资源。为此,它提供了一个基类kubecrd.KubeResourceBase,该类可以将Python数据类转换为Kubernetes自定义资源,并直接在K8s集群中生成和安装这些资源的自定义资源定义。

>>> from dataclasses import dataclass, field
>>> from uuid import UUID
>>> from kubecrd 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=schema(
...            description='regroup multiple resources',
...            unique=False,
...         ),
...     )
>>> print(Resource.crd_schema())
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
<BLANKLINE>

在K8s集群中创建CRD

还可以使用Kubernetes客户端对象在集群中安装CRD

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

然后您可以在集群中找到该资源

» kubectl get crds/resources.example.com
NAME                    CREATED AT
resources.example.com   2022-03-20T03:58:25Z

$ kubectl api-resources | grep example.com
resources     example.com/v1alpha1                  true         Resource

资源安装是幂等的,因此如果传入exist_ok=True,则重新安装已安装的资源不会引发任何异常

Resource.install(k8s_client, exist_ok=True)

序列化

您可以将资源序列化为适合POST到K8s的形式

>>> example = Resource(name='myResource', tags=['tag1', 'tag2'])
>>> import json
>>> print(json.dumps(example.serialize(), sort_keys=True, indent=4))
{
    "apiVersion": "example.com/v1alpha1",
    "kind": "Resource",
    "metadata": {
        "name": "..."
    },
    "spec": {
        "name": "myResource",
        "tags": [
            "tag1",
            "tag2"
        ]
    }
}

对象也可以直接在K8s中序列化和保存

example.save(k8s_client)

在上面的例子中,“client”是Kubernetes客户端对象。您还可以使用kubernetes_asyncio客户端与asyncio一起使用,并执行以下操作

await example.async_save(k8s_async_client)

反序列化

您可以将Kubernetes API的JSON反序列化为Python CR对象。

$ 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"
     ]
 }
 }

通过使用资源的from_json类方法

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

这还加载了Kubernetes的V1ObjectMeta并将其设置为CR的.metadata属性

>>> print(res.metadata.namespace)
default
>>> print(res.metadata.name)
myresource1
>>> print(res.metadata.resource_version)
105572812

监控

可以使用 Kubernetes 的标准 Watch API 监视自定义资源的更改。例如,监视所有资源的更改

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

或者您可以使用 watch 的阻塞同步 API

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

安装

可以使用 pip 或您喜欢的工具从 PyPI 安装 Kube CRD

$ pip install kubecrd

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

kubecrd-0.5.0.tar.gz (10.0 kB 查看哈希值)

上传

构建分发

kubecrd-0.5.0-py3-none-any.whl (9.8 kB 查看哈希值)

上传 Python 3

由以下支持