使用 CustomResourceDefinitions 扩展 Kubernetes API

本页面展示了如何通过创建 CustomResourceDefinition自定义资源安装到 Kubernetes API 中。

准备工作

你需要一个 Kubernetes 集群,并且 kubectl 命令行工具必须配置为与你的集群通信。建议在至少有两个不是控制平面主机的节点上运行本教程。如果你还没有集群,你可以使用 minikube 创建一个,或者使用这些 Kubernetes 游乐场之一。

你的 Kubernetes 服务器版本必须是 1.16 或更高。

要检查版本,请输入 kubectl version

如果你使用的是受支持的旧版 Kubernetes,请切换到该版本的文档以查看与你的集群相关的建议。

创建 CustomResourceDefinition

当你创建新的 CustomResourceDefinition (CRD) 时,Kubernetes API 服务器会为你指定的每个版本创建一个新的 RESTful 资源路径。从 CRD 对象创建的自定义资源可以是命名空间范围的,也可以是集群范围的,具体取决于 CRD 的 spec.scope 字段中指定的值。与现有内置对象一样,删除命名空间会删除该命名空间中的所有自定义对象。CustomResourceDefinition 本身是非命名空间范围的,并且对所有命名空间可用。

例如,如果你将以下 CustomResourceDefinition 保存到 resourcedefinition.yaml

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  # name must match the spec fields below, and be in the form: <plural>.<group>
  name: crontabs.stable.example.com
spec:
  # group name to use for REST API: /apis/<group>/<version>
  group: stable.example.com
  # list of versions supported by this CustomResourceDefinition
  versions:
    - name: v1
      # Each version can be enabled/disabled by Served flag.
      served: true
      # One and only one version must be marked as the storage version.
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                cronSpec:
                  type: string
                image:
                  type: string
                replicas:
                  type: integer
  # either Namespaced or Cluster
  scope: Namespaced
  names:
    # plural name to be used in the URL: /apis/<group>/<version>/<plural>
    plural: crontabs
    # singular name to be used as an alias on the CLI and for display
    singular: crontab
    # kind is normally the CamelCased singular type. Your resource manifests use this.
    kind: CronTab
    # shortNames allow shorter string to match your resource on the CLI
    shortNames:
    - ct

并创建它

kubectl apply -f resourcedefinition.yaml

然后,将在以下位置创建一个新的命名空间范围的 RESTful API 端点:

/apis/stable.example.com/v1/namespaces/*/crontabs/...

此端点 URL 可用于创建和管理自定义对象。这些对象的 kind 将是你在上面创建的 CustomResourceDefinition 对象的规范中的 CronTab

端点可能需要几秒钟才能创建。你可以观察 CustomResourceDefinition 的 Established 条件是否为 true,或观察 API 服务器的发现信息以查看你的资源是否出现。

创建自定义对象

创建 CustomResourceDefinition 对象后,你可以创建自定义对象。自定义对象可以包含自定义字段。这些字段可以包含任意 JSON。在以下示例中,cronSpecimage 自定义字段在 CronTab 类型的自定义对象中设置。CronTab 类型来自你上面创建的 CustomResourceDefinition 对象的规范。

如果你将以下 YAML 保存到 my-crontab.yaml

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  cronSpec: "* * * * */5"
  image: my-awesome-cron-image

并创建它

kubectl apply -f my-crontab.yaml

然后你可以使用 kubectl 管理你的 CronTab 对象。例如

kubectl get crontab

应该打印如下列表

NAME                 AGE
my-new-cron-object   6s

使用 kubectl 时,资源名称不区分大小写,你可以使用 CRD 中定义的单数或复数形式,以及任何短名称。

你还可以查看原始 YAML 数据

kubectl get ct -o yaml

你应该看到它包含你用来创建它的 YAML 中的自定义 cronSpecimage 字段

apiVersion: v1
items:
- apiVersion: stable.example.com/v1
  kind: CronTab
  metadata:
    annotations:
      kubectl.kubernetes.io/last-applied-configuration: |
        {"apiVersion":"stable.example.com/v1","kind":"CronTab","metadata":{"annotations":{},"name":"my-new-cron-object","namespace":"default"},"spec":{"cronSpec":"* * * * */5","image":"my-awesome-cron-image"}}        
    creationTimestamp: "2021-06-20T07:35:27Z"
    generation: 1
    name: my-new-cron-object
    namespace: default
    resourceVersion: "1326"
    uid: 9aab1d66-628e-41bb-a422-57b8b3b1f5a9
  spec:
    cronSpec: '* * * * */5'
    image: my-awesome-cron-image
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""

删除 CustomResourceDefinition

当你删除 CustomResourceDefinition 时,服务器将卸载 RESTful API 端点并删除其中存储的所有自定义对象。

kubectl delete -f resourcedefinition.yaml
kubectl get crontabs
Error from server (NotFound): Unable to list {"stable.example.com" "v1" "crontabs"}: the server could not
find the requested resource (get crontabs.stable.example.com)

如果你稍后重新创建相同的 CustomResourceDefinition,它将从空状态开始。

指定结构化模式

CustomResources 将结构化数据存储在自定义字段中(除了 API 服务器隐式验证的内置字段 apiVersionkindmetadata)。通过 OpenAPI v3.0 验证,可以指定一个模式,该模式在创建和更新期间进行验证,有关此模式的详细信息和限制,请参见下文。

对于 apiextensions.k8s.io/v1,CustomResourceDefinitions 必须定义结构化模式。在 CustomResourceDefinition 的 Beta 版本中,结构化模式是可选的。

结构化模式是 OpenAPI v3.0 验证模式,它

  1. 为根、对象节点的每个指定字段(通过 OpenAPI 中的 propertiesadditionalProperties)和数组节点的每个项(通过 OpenAPI 中的 items)指定一个非空类型(通过 OpenAPI 中的 type),但以下情况除外:
    • 一个带有 x-kubernetes-int-or-string: true 的节点
    • 一个带有 x-kubernetes-preserve-unknown-fields: true 的节点
  2. 对于对象中的每个字段和数组中的每个项,如果在任何 allOfanyOfoneOfnot 中指定,则模式还在这些逻辑连接词之外指定字段/项(比较示例 1 和 2)。
  3. 不在 allOfanyOfoneOfnot 中设置 descriptiontypedefaultadditionalPropertiesnullable,但 x-kubernetes-int-or-string: true 的两种模式除外(见下文)。
  4. 如果指定了 metadata,则只允许对 metadata.namemetadata.generateName 进行限制。

非结构化示例 1

allOf:
- properties:
    foo:
      # ...

与规则 2 冲突。以下是正确的

properties:
  foo:
    # ...
allOf:
- properties:
    foo:
      # ...

非结构化示例 2

allOf:
- items:
    properties:
      foo:
        # ...

与规则 2 冲突。以下是正确的

items:
  properties:
    foo:
      # ...
allOf:
- items:
    properties:
      foo:
        # ...

非结构化示例 3

properties:
  foo:
    pattern: "abc"
  metadata:
    type: object
    properties:
      name:
        type: string
        pattern: "^a"
      finalizers:
        type: array
        items:
          type: string
          pattern: "my-finalizer"
anyOf:
- properties:
    bar:
      type: integer
      minimum: 42
  required: ["bar"]
  description: "foo bar object"

不是结构化模式,因为它存在以下违规

  • 根部的类型缺失(规则 1)。
  • foo 的类型缺失(规则 1)。
  • anyOf 中的 bar 未在外部指定(规则 2)。
  • bartype 位于 anyOf 中(规则 3)。
  • 描述设置在 anyOf 中(规则 3)。
  • metadata.finalizers 可能不受限制(规则 4)。

相比之下,以下对应的模式是结构化的

type: object
description: "foo bar object"
properties:
  foo:
    type: string
    pattern: "abc"
  bar:
    type: integer
  metadata:
    type: object
    properties:
      name:
        type: string
        pattern: "^a"
anyOf:
- properties:
    bar:
      minimum: 42
  required: ["bar"]

结构化模式规则的违规在 CustomResourceDefinition 的 NonStructural 条件中报告。

字段修剪

CustomResourceDefinitions 将经过验证的资源数据存储在集群的持久存储中,即 etcd。与诸如 ConfigMap 等原生 Kubernetes 资源一样,如果你指定了 API 服务器无法识别的字段,则未知字段将在持久化之前被 修剪(删除)。

apiextensions.k8s.io/v1beta1 转换到 apiextensions.k8s.io/v1 的 CRD 可能缺少结构化模式,并且 spec.preserveUnknownFields 可能为 true

对于作为 apiextensions.k8s.io/v1beta1 创建且 spec.preserveUnknownFields 设置为 true 的旧版 CustomResourceDefinition 对象,以下内容也成立:

  • 修剪未启用。
  • 你可以存储任意数据。

为了与 apiextensions.k8s.io/v1 兼容,请更新你的自定义资源定义以

  1. 使用结构化 OpenAPI 模式。
  2. spec.preserveUnknownFields 设置为 false

如果你将以下 YAML 保存到 my-crontab.yaml

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  cronSpec: "* * * * */5"
  image: my-awesome-cron-image
  someRandomField: 42

并创建它

kubectl create --validate=false -f my-crontab.yaml -o yaml

你的输出类似于

apiVersion: stable.example.com/v1
kind: CronTab
metadata:
  creationTimestamp: 2017-05-31T12:56:35Z
  generation: 1
  name: my-new-cron-object
  namespace: default
  resourceVersion: "285"
  uid: 9423255b-4600-11e7-af6a-28d2447dc82b
spec:
  cronSpec: '* * * * */5'
  image: my-awesome-cron-image

请注意,字段 someRandomField 已被修剪。

此示例通过添加 --validate=false 命令行选项来关闭客户端验证,以演示 API 服务器的行为。由于 OpenAPI 验证模式也发布 给客户端,因此 kubectl 也会检查未知字段,并在对象发送到 API 服务器之前将其拒绝。

控制修剪

默认情况下,自定义资源的所有未指定字段(跨所有版本)都会被修剪。但是,可以通过在 结构化 OpenAPI v3 验证模式 中添加 x-kubernetes-preserve-unknown-fields: true 来选择不修剪特定字段子树。

例如

type: object
properties:
  json:
    x-kubernetes-preserve-unknown-fields: true

字段 json 可以存储任何 JSON 值,而不会被修剪。

你还可以部分指定允许的 JSON;例如

type: object
properties:
  json:
    x-kubernetes-preserve-unknown-fields: true
    type: object
    description: this is arbitrary JSON

这样,只允许 object 类型的值。

对于每个指定的属性(或 additionalProperties),修剪再次启用

type: object
properties:
  json:
    x-kubernetes-preserve-unknown-fields: true
    type: object
    properties:
      spec:
        type: object
        properties:
          foo:
            type: string
          bar:
            type: string

这样,值

json:
  spec:
    foo: abc
    bar: def
    something: x
  status:
    something: x

被修剪为

json:
  spec:
    foo: abc
    bar: def
  status:
    something: x

这意味着指定的 spec 对象中的 something 字段被修剪,但外部的一切都没有被修剪。

整型或字符串

模式中带有 x-kubernetes-int-or-string: true 的节点被排除在规则 1 之外,因此以下是结构化的

type: object
properties:
  foo:
    x-kubernetes-int-or-string: true

此外,这些节点也部分排除在规则 3 之外,因为允许以下两种模式(正好是这两种,没有其他字段的变体)

x-kubernetes-int-or-string: true
anyOf:
  - type: integer
  - type: string
...

x-kubernetes-int-or-string: true
allOf:
  - anyOf:
      - type: integer
      - type: string
  - # ... zero or more
...

通过上述任一规范,整数和字符串都有效。

验证模式发布 中,x-kubernetes-int-or-string: true 被展开为上面所示的两种模式之一。

原始扩展

RawExtensions(如 runtime.RawExtension)包含完整的 Kubernetes 对象,即带有 apiVersionkind 字段。

通过设置 x-kubernetes-embedded-resource: true,可以指定这些嵌入式对象(既可以完全不带约束,也可以部分指定)。例如

type: object
properties:
  foo:
    x-kubernetes-embedded-resource: true
    x-kubernetes-preserve-unknown-fields: true

这里,字段 foo 包含一个完整的对象,例如

foo:
  apiVersion: v1
  kind: Pod
  spec:
    # ...

由于同时指定了 x-kubernetes-preserve-unknown-fields: true,因此不会修剪任何内容。但是,使用 x-kubernetes-preserve-unknown-fields: true 是可选的。

通过 x-kubernetes-embedded-resource: trueapiVersionkindmetadata 被隐式指定和验证。

提供多个 CRD 版本

有关提供 CustomResourceDefinition 多个版本以及将对象从一个版本迁移到另一个版本的更多信息,请参阅 Custom resource definition versioning

高级主题

终结器

终结器(Finalizers) 允许控制器实现异步预删除钩子。自定义对象支持与内置对象类似的终结器。

你可以像这样向自定义对象添加终结器

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  finalizers:
  - stable.example.com/finalizer

自定义终结器的标识符由域名、正斜杠和终结器名称组成。任何控制器都可以将终结器添加到任何对象的终结器列表中。

对具有终结器对象进行的第一次删除请求会为 metadata.deletionTimestamp 字段设置一个值,但不会删除它。一旦设置了此值,finalizers 列表中的条目只能被移除。在任何终结器仍然存在的情况下,也无法强制删除对象。

当设置了 metadata.deletionTimestamp 字段后,监视对象的控制器会执行它们处理的所有终结器,并在完成后将终结器从列表中移除。每个控制器都有责任从列表中移除其终结器。

metadata.deletionGracePeriodSeconds 的值控制轮询更新的间隔。

一旦终结器列表为空,即所有终结器都已执行完毕,Kubernetes 将删除该资源。

验证

自定义资源通过 OpenAPI v3.0 模式进行验证,当启用 验证规则功能 时通过 x-kubernetes-validations 进行验证,你还可以使用 准入 Webhook 添加额外的验证。

此外,以下限制适用于模式

  • 这些字段不能设置

    • definitions,
    • dependencies,
    • deprecated,
    • discriminator,
    • id,
    • patternProperties,
    • readOnly,
    • writeOnly,
    • xml,
    • $ref.
  • 字段 uniqueItems 不能设置为 true

  • 字段 additionalProperties 不能设置为 false

  • 字段 additionalPropertiesproperties 互斥。

验证规则 功能启用且 CustomResourceDefinition 模式是 结构化模式 时,x-kubernetes-validations 扩展可用于使用 通用表达式语言 (CEL) 表达式验证自定义资源。

有关其他限制和 CustomResourceDefinition 功能,请参阅 结构化模式 部分。

模式在 CustomResourceDefinition 中定义。在以下示例中,CustomResourceDefinition 对自定义对象应用以下验证

  • spec.cronSpec 必须是字符串,并且必须符合正则表达式描述的形式。
  • spec.replicas 必须是整数,并且最小值必须为 1,最大值必须为 10。

将 CustomResourceDefinition 保存到 resourcedefinition.yaml

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: crontabs.stable.example.com
spec:
  group: stable.example.com
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        # openAPIV3Schema is the schema for validating custom objects.
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                cronSpec:
                  type: string
                  pattern: '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
                image:
                  type: string
                replicas:
                  type: integer
                  minimum: 1
                  maximum: 10
  scope: Namespaced
  names:
    plural: crontabs
    singular: crontab
    kind: CronTab
    shortNames:
    - ct

并创建它

kubectl apply -f resourcedefinition.yaml

如果其字段中存在无效值,则创建 CronTab 类型自定义对象的请求将被拒绝。在以下示例中,自定义对象包含具有无效值的字段

  • spec.cronSpec 与正则表达式不匹配。
  • spec.replicas 大于 10。

如果你将以下 YAML 保存到 my-crontab.yaml

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  cronSpec: "* * * *"
  image: my-awesome-cron-image
  replicas: 15

并尝试创建它

kubectl apply -f my-crontab.yaml

然后你会得到一个错误

The CronTab "my-new-cron-object" is invalid: []: Invalid value: map[string]interface {}{"apiVersion":"stable.example.com/v1", "kind":"CronTab", "metadata":map[string]interface {}{"name":"my-new-cron-object", "namespace":"default", "deletionTimestamp":interface {}(nil), "deletionGracePeriodSeconds":(*int64)(nil), "creationTimestamp":"2017-09-05T05:20:07Z", "uid":"e14d79e7-91f9-11e7-a598-f0761cb232d1", "clusterName":""}, "spec":map[string]interface {}{"cronSpec":"* * * *", "image":"my-awesome-cron-image", "replicas":15}}:
validation failure list:
spec.cronSpec in body should match '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
spec.replicas in body should be less than or equal to 10

如果字段包含有效值,则对象创建请求将被接受。

将以下 YAML 保存到 my-crontab.yaml

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  cronSpec: "* * * * */5"
  image: my-awesome-cron-image
  replicas: 5

并创建它

kubectl apply -f my-crontab.yaml
crontab "my-new-cron-object" created

验证棘轮机制

特性状态: Kubernetes v1.33 [stable] (默认启用:true)

如果你使用的是低于 v1.30 的 Kubernetes 版本,则需要显式启用 CRDValidationRatcheting 功能门 才能使用此行为,然后此行为将应用于集群中的所有 CustomResourceDefinition。

如果你启用了功能门,Kubernetes 会为 CustomResourceDefinitions 实现 验证棘轮机制。API 服务器愿意接受对更新后无效的资源的更新,前提是资源中未能通过验证的每个部分在更新操作中都没有更改。换句话说,资源中任何仍然无效的无效部分都必须已经是错误的。你不能使用此机制来更新有效资源使其变为无效。

此功能允许 CRD 作者在某些条件下自信地向 OpenAPIV3 模式添加新的验证。用户可以安全地更新到新模式,而无需增加对象的版本或破坏工作流。

尽管 CRD 的 OpenAPIV3 模式中放置的大多数验证都支持棘轮机制,但也有一些例外。以下 OpenAPIV3 模式验证在 Kubernetes 1.34 的实现中不支持棘轮机制,如果违反,将像往常一样继续抛出错误:

  • 量词

    • allOf
    • oneOf
    • anyOf
    • not
    • 这些字段的任何后代中的任何验证
  • x-kubernetes-validations 对于 Kubernetes 1.28,CRD 验证规则 被棘轮机制忽略。从 Kubernetes 1.29 的 Alpha 2 开始,只有当 x-kubernetes-validations 不引用 oldSelf 时,它们才会被棘轮机制处理。

    过渡规则从不被棘轮机制处理:只有那些不使用 oldSelf 的规则所引发的错误,如果它们的值未改变,才会自动被棘轮机制处理。

    要为 CEL 表达式编写自定义的棘轮逻辑,请查看 optionalOldSelf

  • x-kubernetes-list-type 因更改子模式的列表类型而产生的错误将不会被棘轮化。例如,在包含重复项的列表中添加 set 将始终导致错误。

  • x-kubernetes-list-map-keys 因更改列表模式的映射键而产生的错误将不会被棘轮化。

  • required 因更改必填字段列表而产生的错误将不会被棘轮化。

  • properties 添加/删除/修改属性名称不会被棘轮化,但如果属性名称保持不变,则对每个属性的模式和子模式中的验证进行更改可能会被棘轮化。

  • additionalProperties 移除以前指定的 additionalProperties 验证将不会被棘轮化。

  • metadata 来自 Kubernetes 对对象 metadata 的内置验证的错误不会被棘轮化(例如对象名称或标签值中的字符)。如果你为自定义资源的元数据指定了自己额外的规则,则该额外验证将被棘轮化。

验证规则

特性状态: Kubernetes v1.29 [stable]

验证规则使用 通用表达式语言 (CEL) 来验证自定义资源值。验证规则通过 x-kubernetes-validations 扩展包含在 CustomResourceDefinition 模式中。

该规则的作用域是模式中 x-kubernetes-validations 扩展的位置。CEL 表达式中的 self 变量绑定到作用域值。

所有验证规则都作用于当前对象:不支持跨对象或有状态的验证规则。

例如

  # ...
  openAPIV3Schema:
    type: object
    properties:
      spec:
        type: object
        x-kubernetes-validations:
          - rule: "self.minReplicas <= self.replicas"
            message: "replicas should be greater than or equal to minReplicas."
          - rule: "self.replicas <= self.maxReplicas"
            message: "replicas should be smaller than or equal to maxReplicas."
        properties:
          # ...
          minReplicas:
            type: integer
          replicas:
            type: integer
          maxReplicas:
            type: integer
        required:
          - minReplicas
          - replicas
          - maxReplicas

将拒绝创建此自定义资源的请求

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  minReplicas: 0
  replicas: 20
  maxReplicas: 10

响应为

The CronTab "my-new-cron-object" is invalid:
* spec: Invalid value: map[string]interface {}{"maxReplicas":10, "minReplicas":0, "replicas":20}: replicas should be smaller than or equal to maxReplicas.

x-kubernetes-validations 可以有多个规则。x-kubernetes-validations 下的 rule 表示将由 CEL 评估的表达式。message 表示验证失败时显示的消息。如果未设置消息,则上述响应将是

The CronTab "my-new-cron-object" is invalid:
* spec: Invalid value: map[string]interface {}{"maxReplicas":10, "minReplicas":0, "replicas":20}: failed rule: self.replicas <= self.maxReplicas

验证规则在 CRD 创建/更新时编译。如果验证规则编译失败,则 CRD 创建/更新请求将失败。编译过程还包括类型检查。

编译失败

  • no_matching_overload:此函数没有参数类型的重载。

    例如,针对整数类型的字段的规则 self == true 将收到错误

    Invalid value: apiextensions.ValidationRule{Rule:"self == true", Message:""}: compilation failed: ERROR: \<input>:1:6: found no matching overload for '_==_' applied to '(int, bool)'
    
  • no_such_field:不包含所需的字段。

    例如,针对不存在的字段的规则 self.nonExistingField > 0 将返回以下错误

    Invalid value: apiextensions.ValidationRule{Rule:"self.nonExistingField > 0", Message:""}: compilation failed: ERROR: \<input>:1:5: undefined field 'nonExistingField'
    
  • invalid argument:宏的无效参数。

    例如,规则 has(self) 将返回错误

    Invalid value: apiextensions.ValidationRule{Rule:"has(self)", Message:""}: compilation failed: ERROR: <input>:1:4: invalid argument to has() macro
    

验证规则示例

规则目的
self.minReplicas <= self.replicas && self.replicas <= self.maxReplicas验证定义副本的三个字段是否按适当顺序排列
'Available' in self.stateCounts验证映射中是否存在带有“Available”键的条目
(size(self.list1) == 0) != (size(self.list2) == 0)验证两个列表中的一个非空,但不能都非空
!('MY_KEY' in self.map1) || self['MY_KEY'].matches('^[a-zA-Z]*$')验证映射中特定键的值(如果存在)
self.envars.filter(e, e.name == 'MY_ENV').all(e, e.value.matches('^[a-zA-Z]*$')验证键字段“name”为“MY_ENV”的 listMap 条目的“value”字段
has(self.expired) && self.created + self.ttl < self.expired验证“expired”日期是否晚于“create”日期加上“ttl”持续时间
self.health.startsWith('ok')验证“health”字符串字段是否具有前缀“ok”
self.widgets.exists(w, w.key == 'x' && w.foo < 10)验证键为“x”的 listMap 项的“foo”属性是否小于 10
type(self) == string ? self == '100%' : self == 1000验证 int-or-string 字段的整数和字符串情况
self.metadata.name.startsWith(self.prefix)验证对象的名称是否具有另一个字段值的前缀
self.set1.all(e, !(e in self.set2))验证两个 listSet 是否不相交
size(self.names) == size(self.details) && self.names.all(n, n in self.details)验证“details”映射是否由“names”listSet 中的项作为键
size(self.clusters.filter(c, c.name == self.primary)) == 1验证“primary”属性在“clusters”listMap 中是否存在且仅存在一次

交叉引用:CEL 上支持的评估

  • 如果规则的作用域是资源的根,则它可以对 CRD 的 OpenAPIv3 模式中声明的任何字段以及 apiVersionkindmetadata.namemetadata.generateName 进行字段选择。这包括在同一个表达式中选择 specstatus 中的字段

      # ...
      openAPIV3Schema:
        type: object
        x-kubernetes-validations:
          - rule: "self.status.availableReplicas >= self.spec.minReplicas"
        properties:
            spec:
              type: object
              properties:
                minReplicas:
                  type: integer
                # ...
            status:
              type: object
              properties:
                availableReplicas:
                  type: integer
    
  • 如果规则的作用域是一个具有属性的对象,则该对象的可用属性可以通过 self.field 进行字段选择,并且可以通过 has(self.field) 检查字段是否存在。在 CEL 表达式中,null 值字段被视为不存在的字段。

      # ...
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            x-kubernetes-validations:
              - rule: "has(self.foo)"
            properties:
              # ...
              foo:
                type: integer
    
  • 如果规则的作用域是一个具有额外属性(即映射)的对象,则可以通过 self[mapKey] 访问映射的值,可以通过 mapKey in self 检查映射的包含性,并且可以通过 CEL 宏和函数(例如 self.all(...))访问映射的所有条目。

      # ...
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            x-kubernetes-validations:
              - rule: "self['xyz'].foo > 0"
            additionalProperties:
              # ...
              type: object
              properties:
                foo:
                  type: integer
    
  • 如果规则的作用域是一个数组,则可以通过 self[i] 以及宏和函数访问数组的元素。

      # ...
      openAPIV3Schema:
        type: object
        properties:
          # ...
          foo:
            type: array
            x-kubernetes-validations:
              - rule: "size(self) == 1"
            items:
              type: string
    
  • 如果规则的作用域是标量,则 self 绑定到标量值。

      # ...
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            properties:
              # ...
              foo:
                type: integer
                x-kubernetes-validations:
                - rule: "self > 0"
    

示例

字段规则的作用域类型规则示例
根对象self.status.actual <= self.spec.maxDesired
对象映射self.components['Widget'].priority < 10
整数列表self.values.all(value, value >= 0 && value < 100)
stringself.startsWith('kube')

apiVersionkindmetadata.namemetadata.generateName 始终可从对象的根和任何带有 x-kubernetes-embedded-resource 注释的对象访问。其他元数据属性不可访问。

通过 x-kubernetes-preserve-unknown-fields 在自定义资源中保留的未知数据在 CEL 表达式中不可访问。这包括

  • 通过具有 x-kubernetes-preserve-unknown-fields 的对象模式保留的未知字段值。

  • 属性模式为“未知类型”的对象属性。“未知类型”递归定义为

    • 没有类型且 x-kubernetes-preserve-unknown-fields 设置为 true 的模式
    • 其项模式为“未知类型”的数组
    • additionalProperties 模式为“未知类型”的对象

只有格式为 [a-zA-Z_.-/][a-zA-Z0-9_.-/]* 的属性名称可以访问。在表达式中访问时,可访问的属性名称根据以下规则进行转义

转义序列等效属性名称
__underscores____
__dot__.
__dash__-
__slash__/
__{keyword}__CEL RESERVED 关键字

注意:CEL RESERVED 关键字需要与要转义的精确属性名称匹配(例如,单词 sprint 中的 int 不会被转义)。

转义示例

属性名称带转义属性名称的规则
命名空间self.__namespace__ > 0
x-propself.x__dash__prop > 0
redact__dself.redact__underscores__d > 0
stringself.startsWith('kube')

具有 x-kubernetes-list-typesetmap 的数组上的相等性会忽略元素顺序,即 [1, 2] == [2, 1]。具有 x-kubernetes-list-type 的数组上的连接使用列表类型的语义

  • setX + Y 执行并集操作,其中 X 中所有元素的数组位置保持不变,并且 Y 中不相交的元素被追加,保留其部分顺序。

  • mapX + Y 执行合并操作,其中 X 中所有键的数组位置保持不变,但当 XY 的键集相交时,值会被 Y 中的值覆盖。Y 中具有不相交键的元素被追加,保留其部分顺序。

以下是 OpenAPIv3 和 CEL 类型之间的声明类型映射

OpenAPIv3 类型CEL 类型
'object' with Properties对象 / "消息类型"
'object' with AdditionalProperties映射
'object' with x-kubernetes-embedded-type对象 / "消息类型",'apiVersion'、'kind'、'metadata.name' 和 'metadata.generateName' 隐式包含在模式中
'object' with x-kubernetes-preserve-unknown-fields对象 / "消息类型",未知字段在 CEL 表达式中不可访问
x-kubernetes-int-or-string动态对象,可以是整数或字符串,type(value) 可用于检查类型
'arraylist
'array' with x-kubernetes-list-type=map具有基于映射的相等性和唯一键保证的列表
'array' with x-kubernetes-list-type=set具有基于集合的相等性和唯一条目保证的列表
'boolean'布尔值
'number' (所有格式)双精度浮点数
'integer' (所有格式)整数 (64)
'null'null 类型
'string'string
'string' with format=byte (base64 编码)字节
'string' with format=date时间戳 (google.protobuf.Timestamp)
'string' with format=datetime时间戳 (google.protobuf.Timestamp)
'string' with format=duration持续时间 (google.protobuf.Duration)

交叉引用:CEL 类型OpenAPI 类型Kubernetes 结构化模式

messageExpression 字段

message 字段类似,它定义了验证规则失败时报告的字符串,messageExpression 允许你使用 CEL 表达式来构造消息字符串。这使你可以在验证失败消息中插入更具描述性的信息。messageExpression 必须评估为字符串,并且可以使用与 rule 字段相同的变量。例如

x-kubernetes-validations:
- rule: "self.x <= self.maxLimit"
  messageExpression: '"x exceeded max limit of " + string(self.maxLimit)'

请记住,CEL 字符串连接(+ 运算符)不会自动转换为字符串。如果你有一个非字符串标量,请使用 string(<value>) 函数将标量转换为字符串,如上例所示。

messageExpression 必须评估为字符串,并且在写入 CRD 时进行检查。请注意,可以在同一规则上设置 messagemessageExpression,如果两者都存在,则将使用 messageExpression。但是,如果 messageExpression 评估为错误,则将使用 message 中定义的字符串,并且将记录 messageExpression 错误。如果 messageExpression 中定义的 CEL 表达式生成空字符串或包含换行符的字符串,也会发生此回退。

如果满足上述条件之一且未设置 message,则将使用默认的验证失败消息。

messageExpression 是一个 CEL 表达式,因此 验证函数使用的资源 中列出的限制适用。如果在 messageExpression 执行期间由于资源限制而停止评估,则不会执行任何进一步的验证规则。

设置 messageExpression 是可选的。

message 字段

如果你想设置静态消息,可以提供 message 而不是 messageExpression。如果验证失败,message 的值将用作不透明的错误字符串。

设置 message 是可选的。

reason 字段

你可以在 validation 中添加一个机器可读的验证失败原因,以便在请求未能通过此验证规则时返回。

例如

x-kubernetes-validations:
- rule: "self.x <= self.maxLimit"
  reason: "FieldValueInvalid"

返回给调用者的 HTTP 状态码将与第一个失败验证规则的原因匹配。目前支持的原因有:“FieldValueInvalid”、“FieldValueForbidden”、“FieldValueRequired”、“FieldValueDuplicate”。如果未设置或原因未知,则默认为“FieldValueInvalid”。

设置 reason 是可选的。

fieldPath 字段

你可以指定验证失败时返回的字段路径。

例如

x-kubernetes-validations:
- rule: "self.foo.test.x <= self.maxLimit"
  fieldPath: ".foo.test.x"

在上面的例子中,验证检查字段 x 的值是否小于 maxLimit 的值。如果没有指定 fieldPath,当验证失败时,fieldPath 将默认为 self 的作用域。如果指定了 fieldPath,返回的错误将正确引用字段 x 的位置。

fieldPath 值必须是相对 JSON 路径,其作用域为模式中 x-kubernetes-validations 扩展的位置。此外,它应该引用模式中已存在的字段。例如,当验证检查映射 testMap 下的特定属性 foo 时,你可以将 fieldPath 设置为 ".testMap.foo".testMap['foo']'。如果验证需要检查两个列表中唯一的属性,则 fieldPath 可以设置为任一列表。例如,它可以设置为 .testList1.testList2。目前它支持子操作以引用现有字段。有关更多信息,请参阅 Kubernetes 中的 JSONPath 支持fieldPath 字段不支持按数字索引数组。

设置 fieldPath 是可选的。

optionalOldSelf 字段

特性状态: Kubernetes v1.33 [stable] (默认启用:true)

如果你的集群未启用 CRD 验证棘轮机制,则 CustomResourceDefinition API 不包含此字段,尝试设置它可能会导致错误。

optionalOldSelf 字段是一个布尔字段,它改变了下面描述的 过渡规则 的行为。通常,如果无法确定 oldSelf(在对象创建期间或在更新中引入新值时),则过渡规则将不会评估。

如果 optionalOldSelf 设置为 true,则过渡规则将始终被评估,并且 oldSelf 的类型将更改为 CEL Optional 类型。

optionalOldSelf 在模式作者希望通过比 默认的基于等价的行为 提供更多控制工具来对新值引入新的(通常更严格的)约束,同时仍然允许使用旧的验证来“祖父”或棘轮化旧值的情况下非常有用。

使用示例

CEL描述
self.foo == "foo" || (oldSelf.hasValue() && oldSelf.value().foo != "foo")棘轮规则。一旦值设置为“foo”,它必须保持为 foo。但如果它在引入“foo”约束之前存在,则可以使用任何值
[oldSelf.orValue(""), self].all(x, ["OldCase1", "OldCase2"].exists(case, x == case)) || ["NewCase1", "NewCase2"].exists(case, self == case) || ["NewCase"].has(self)“如果 oldSelf 使用了被删除的枚举案例,则对这些案例进行棘轮验证”
oldSelf.optMap(o, o.size()).orValue(0) < 4 || self.size() >= 4新增加的最小映射或列表大小的棘轮验证

验证函数

可用函数包括

过渡规则

包含引用标识符 oldSelf 的表达式的规则被隐式视为 过渡规则。过渡规则允许模式作者阻止两个原本有效状态之间的某些过渡。例如

type: string
enum: ["low", "medium", "high"]
x-kubernetes-validations:
- rule: "!(self == 'high' && oldSelf == 'low') && !(self == 'low' && oldSelf == 'high')"
  message: cannot transition directly between 'low' and 'high'

与其他规则不同,过渡规则仅适用于满足以下条件的操作

  • 该操作更新现有对象。过渡规则从不适用于创建操作。

  • 新旧值都存在。仍然可以通过在父节点上放置过渡规则来检查是否已添加或删除了值。过渡规则从不适用于自定义资源创建。当放置在可选字段上时,过渡规则不适用于设置或取消设置字段的更新操作。

  • 用于验证过渡规则的模式节点的路径必须解析为在旧对象和新对象之间可比较的节点。例如,列表项及其后代 (spec.foo[10].bar) 不一定可以在现有对象和对同一对象的后续更新之间进行关联。

如果模式节点包含无法应用的过渡规则(例如,“旧 Self 不能在模式中不可关联的部分中使用 path”),则会在 CRD 写入时生成错误。

过渡规则仅允许在模式的 可关联部分 上使用。如果所有 array 父模式的类型都是 x-kubernetes-list-type=map,则模式的一部分是可关联的;任何 setatomic 数组父模式都使得无法明确地将 selfoldSelf 关联。

以下是一些过渡规则的示例

过渡规则示例
用例规则
不变性self.foo == oldSelf.foo
一旦赋值,阻止修改/删除oldSelf != 'bar' || self == 'bar'!has(oldSelf.field) || has(self.field)
仅追加集合self.all(element, element in oldSelf)
如果旧值是 X,新值只能是 A 或 B,不能是 Y 或 ZoldSelf != 'X' || self in ['A', 'B']
单调(非递减)计数器self >= oldSelf

验证函数使用的资源

当你创建或更新使用验证规则的 CustomResourceDefinition 时,API 服务器会检查运行这些验证规则的可能影响。如果某个规则被认为执行成本过高,API 服务器将拒绝创建或更新操作,并返回错误消息。运行时使用类似的系统来观察解释器执行的操作。如果解释器执行的指令过多,规则的执行将被停止,并导致错误。每个 CustomResourceDefinition 也被允许使用一定量的资源来完成其所有验证规则的执行。如果在创建时估计其规则的总和超过该限制,则也会发生验证错误。

如果你只指定始终花费相同时间(无论输入大小如何)的规则,则不太可能遇到验证资源预算问题。例如,一个断言 self.foo == 1 的规则本身没有因验证资源预算组而被拒绝的风险。但是,如果 foo 是一个字符串,并且你定义了一个验证规则 self.foo.contains("someString"),则该规则的执行时间会根据 foo 的长度而变化。另一个示例是如果 foo 是一个数组,并且你指定了一个验证规则 self.foo.all(x, x > 5)。如果未给出 foo 长度的限制,则成本系统始终假定最坏情况,并且对于任何可迭代的内容(列表、映射等)都会发生这种情况。

因此,最佳实践是通过 maxItemsmaxPropertiesmaxLength 对将在验证规则中处理的任何内容设置限制,以防止在成本估算过程中出现验证错误。例如,给定以下具有一个规则的模式

openAPIV3Schema:
  type: object
  properties:
    foo:
      type: array
      items:
        type: string
      x-kubernetes-validations:
        - rule: "self.all(x, x.contains('a string'))"

则 API 服务器将因验证预算原因拒绝此规则,并返回错误

spec.validation.openAPIV3Schema.properties[spec].properties[foo].x-kubernetes-validations[0].rule: Forbidden:
CEL rule exceeded budget by more than 100x (try simplifying the rule, or adding maxItems, maxProperties, and
maxLength where arrays, maps, and strings are used)

拒绝发生的原因是 self.all 意味着对 foo 中的每个字符串调用 contains(),这反过来会检查给定字符串是否包含 'a string'。如果没有限制,这是一个非常昂贵的规则。

如果你未指定任何验证限制,则此规则的估计成本将超过每条规则的成本限制。但如果你在适当的位置添加限制,则该规则将被允许

openAPIV3Schema:
  type: object
  properties:
    foo:
      type: array
      maxItems: 25
      items:
        type: string
        maxLength: 10
      x-kubernetes-validations:
        - rule: "self.all(x, x.contains('a string'))"

成本估算系统会考虑规则将被执行的次数以及规则本身的估计成本。例如,以下规则的估计成本与上一个示例相同(尽管现在在单个数组项上定义了规则)

openAPIV3Schema:
  type: object
  properties:
    foo:
      type: array
      maxItems: 25
      items:
        type: string
        x-kubernetes-validations:
          - rule: "self.contains('a string'))"
        maxLength: 10

如果列表中的列表具有使用 self.all 的验证规则,则其成本显著高于具有相同规则的非嵌套列表。在一个非嵌套列表上允许的规则可能需要对两个嵌套列表设置较低的限制才能被允许。例如,即使没有设置限制,以下规则也是允许的

openAPIV3Schema:
  type: object
  properties:
    foo:
      type: array
      items:
        type: integer
    x-kubernetes-validations:
      - rule: "self.all(x, x == 5)"

但是,在以下模式(添加了嵌套数组)上使用相同的规则会产生验证错误

openAPIV3Schema:
  type: object
  properties:
    foo:
      type: array
      items:
        type: array
        items:
          type: integer
        x-kubernetes-validations:
          - rule: "self.all(x, x == 5)"

这是因为 foo 的每个项本身都是一个数组,并且每个子数组又调用 self.all。如果使用验证规则,请尽可能避免嵌套列表和映射。

默认值

默认值允许在 OpenAPI v3 验证模式 中指定默认值

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: crontabs.stable.example.com
spec:
  group: stable.example.com
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        # openAPIV3Schema is the schema for validating custom objects.
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                cronSpec:
                  type: string
                  pattern: '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
                  default: "5 0 * * *"
                image:
                  type: string
                replicas:
                  type: integer
                  minimum: 1
                  maximum: 10
                  default: 1
  scope: Namespaced
  names:
    plural: crontabs
    singular: crontab
    kind: CronTab
    shortNames:
    - ct

这样 cronSpecreplicas 都将被默认设置

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  image: my-awesome-cron-image

导致

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  cronSpec: "5 0 * * *"
  image: my-awesome-cron-image
  replicas: 1

默认值在对象上发生

  • 在使用请求版本的默认值向 API 服务器发出请求时,
  • 从 etcd 读取时使用存储版本的默认值,
  • 在具有非空补丁的变异准入插件之后使用准入 webhook 对象版本默认值。

从 etcd 读取数据时应用的默认值不会自动写回 etcd。需要通过 API 发出更新请求才能将这些默认值持久化回 etcd。

非叶子字段的默认值必须被修剪(metadata 字段的默认值除外),并且必须根据提供的模式进行验证。例如,在上面的示例中,spec 字段的默认值 {"replicas": "foo", "badger": 1} 将无效,因为 badger 是一个未知字段,并且 replicas 不是字符串。

x-kubernetes-embedded-resources: true 节点的 metadata 字段(或覆盖 metadata 的默认值的一部分)的默认值在 CustomResourceDefinition 创建期间不会被修剪,而是在请求处理期间通过修剪步骤进行修剪。

默认值和可空性

对于未指定 nullable 标志或将其设置为 false 的字段,null 值将在默认值发生之前被修剪。如果存在默认值,它将被应用。当 nullable 为 true 时,null 值将被保留并且不会被默认设置。

例如,给定下面的 OpenAPI 模式

type: object
properties:
  spec:
    type: object
    properties:
      foo:
        type: string
        nullable: false
        default: "default"
      bar:
        type: string
        nullable: true
      baz:
        type: string

创建 foobarbaz 具有 null 值的对象

spec:
  foo: null
  bar: null
  baz: null

导致

spec:
  foo: "default"
  bar: null

其中 foo 被修剪并默认设置,因为该字段不可为空,bar 由于 nullable: true 而保留 null 值,而 baz 被修剪,因为该字段不可为空且没有默认值。

在 OpenAPI 中发布验证模式

CustomResourceDefinition OpenAPI v3 验证模式,如果它们是 结构化的启用修剪,则会作为 OpenAPI v3 和 OpenAPI v2 从 Kubernetes API 服务器发布。建议使用 OpenAPI v3 文档,因为它无损地表示 CustomResourceDefinition OpenAPI v3 验证模式,而 OpenAPI v2 表示有损转换。

kubectl 命令行工具会使用已发布的模式对自定义资源执行客户端验证 (kubectl createkubectl apply) 和模式解释 (kubectl explain)。已发布的模式还可以用于其他目的,例如客户端生成或文档。

与 OpenAPI V2 的兼容性

为了与 OpenAPI V2 兼容,OpenAPI v3 验证模式会对 OpenAPI v2 模式进行有损转换。该模式显示在 OpenAPI v2 规范definitionspaths 字段中。

在转换为保持与早期 1.13 版本中 kubectl 向后兼容期间,会应用以下修改。这些修改可防止 kubectl 过于严格并拒绝它不理解的有效 OpenAPI 模式。转换不会修改 CRD 中定义的验证模式,因此不会影响 API 服务器中的 验证

  1. 以下字段因 OpenAPI v2 不支持而被移除。

    • 字段 allOfanyOfoneOfnot 被移除
  2. 如果设置了 nullable: true,我们将删除 typenullableitemsproperties,因为 OpenAPI v2 无法表达可空性。为了避免 kubectl 拒绝好的对象,这是必要的。

额外的打印列

kubectl 工具依赖于服务器端输出格式。集群的 API 服务器决定 kubectl get 命令显示哪些列。你可以为 CustomResourceDefinition 自定义这些列。以下示例添加了 SpecReplicasAge 列。

将 CustomResourceDefinition 保存到 resourcedefinition.yaml

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: crontabs.stable.example.com
spec:
  group: stable.example.com
  scope: Namespaced
  names:
    plural: crontabs
    singular: crontab
    kind: CronTab
    shortNames:
    - ct
  versions:
  - name: v1
    served: true
    storage: true
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            properties:
              cronSpec:
                type: string
              image:
                type: string
              replicas:
                type: integer
    additionalPrinterColumns:
    - name: Spec
      type: string
      description: The cron spec defining the interval a CronJob is run
      jsonPath: .spec.cronSpec
    - name: Replicas
      type: integer
      description: The number of jobs launched by the CronJob
      jsonPath: .spec.replicas
    - name: Age
      type: date
      jsonPath: .metadata.creationTimestamp

创建 CustomResourceDefinition

kubectl apply -f resourcedefinition.yaml

使用上一节中的 my-crontab.yaml 创建一个实例。

调用服务器端打印

kubectl get crontab my-new-cron-object

注意输出中的 NAMESPECREPLICASAGE

NAME                 SPEC        REPLICAS   AGE
my-new-cron-object   * * * * *   1          7s

优先级

每列都包含一个 priority 字段。目前,优先级区分标准视图或宽视图(使用 -o wide 标志)中显示的列。

  • 优先级为 0 的列显示在标准视图中。
  • 优先级大于 0 的列仅在宽视图中显示。

类型

列的 type 字段可以是以下任何一种(比较 OpenAPI v3 数据类型

  • integer – 非浮点数
  • number – 浮点数
  • string – 字符串
  • booleantruefalse
  • date – 作为自此时间戳以来的时间差呈现。

如果 CustomResource 中的值与为列指定的类型不匹配,则该值将被省略。使用 CustomResource 验证以确保值类型正确。

格式

列的 format 字段可以是以下任何一种

  • int32
  • int64
  • float
  • 双精度浮点数
  • byte
  • date
  • date-time
  • password

列的 format 控制 kubectl 打印值时使用的样式。

字段选择器

字段选择器 允许客户端根据一个或多个资源字段的值选择自定义资源。

所有自定义资源都支持 metadata.namemetadata.namespace 字段选择器。

CustomResourceDefinition 中声明的字段,当包含在 CustomResourceDefinitionspec.versions[*].selectableFields 字段中时,也可以与字段选择器一起使用。

自定义资源的可选择字段

特性状态: Kubernetes v1.32 [stable] (默认启用:true)

CustomResourceDefinitionspec.versions[*].selectableFields 字段可用于声明自定义资源中的哪些其他字段可以使用 CustomResourceFieldSelectors 特性门控(此特性门控自 Kubernetes v1.31 起默认启用)在字段选择器中使用。以下示例将 .spec.color.spec.size 字段添加为可选择字段。

将 CustomResourceDefinition 保存到 shirt-resource-definition.yaml

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: shirts.stable.example.com
spec:
  group: stable.example.com
  scope: Namespaced
  names:
    plural: shirts
    singular: shirt
    kind: Shirt
  versions:
  - name: v1
    served: true
    storage: true
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            type: object
            properties:
              color:
                type: string
              size:
                type: string
    selectableFields:
    - jsonPath: .spec.color
    - jsonPath: .spec.size
    additionalPrinterColumns:
    - jsonPath: .spec.color
      name: Color
      type: string
    - jsonPath: .spec.size
      name: Size
      type: string

创建 CustomResourceDefinition

kubectl apply -f https://k8s.io/examples/customresourcedefinition/shirt-resource-definition.yaml

通过编辑 shirt-resources.yaml 定义一些衬衫;例如

---
apiVersion: stable.example.com/v1
kind: Shirt
metadata:
  name: example1
spec:
  color: blue
  size: S
---
apiVersion: stable.example.com/v1
kind: Shirt
metadata:
  name: example2
spec:
  color: blue
  size: M
---
apiVersion: stable.example.com/v1
kind: Shirt
metadata:
  name: example3
spec:
  color: green
  size: M

创建自定义资源

kubectl apply -f https://k8s.io/examples/customresourcedefinition/shirt-resources.yaml

获取所有资源

kubectl get shirts.stable.example.com

输出为:

NAME       COLOR  SIZE
example1   blue   S
example2   blue   M
example3   green  M

获取蓝色衬衫(检索 colorblue 的衬衫)

kubectl get shirts.stable.example.com --field-selector spec.color=blue

应输出

NAME       COLOR  SIZE
example1   blue   S
example2   blue   M

仅获取 colorgreensizeM 的资源

kubectl get shirts.stable.example.com --field-selector spec.color=green,spec.size=M

应输出

NAME       COLOR  SIZE
example2   blue   M

子资源

自定义资源支持 /status/scale 子资源。

通过在 CustomResourceDefinition 中定义它们,可以选择性地启用状态和扩缩子资源。

状态子资源

当状态子资源启用时,将暴露自定义资源的 /status 子资源。

  • 状态和规约节分别由自定义资源内部的 .status.spec JSONPath 表示。

  • /status 子资源的 PUT 请求接受一个自定义资源对象,并忽略除了状态节之外的所有更改。

  • /status 子资源的 PUT 请求仅验证自定义资源的状态节。

  • 对自定义资源的 PUT/POST/PATCH 请求忽略状态节的更改。

  • 除了对 .metadata.status 的更改外,.metadata.generation 值将针对所有更改递增。

  • CRD OpenAPI 验证模式的根目录中只允许以下结构

    • description
    • example
    • exclusiveMaximum
    • exclusiveMinimum
    • externalDocs
    • format
    • items
    • maximum
    • maxItems
    • maxLength
    • minimum
    • minItems
    • minLength
    • multipleOf
    • pattern
    • properties
    • required
    • title
    • type
    • uniqueItems

扩缩子资源

当扩缩子资源启用时,将暴露自定义资源的 /scale 子资源。autoscaling/v1.Scale 对象作为 /scale 的负载发送。

要启用扩缩子资源,需要在 CustomResourceDefinition 中定义以下字段。

  • specReplicasPath 定义了自定义资源中与 scale.spec.replicas 对应的 JSONPath。

    • 它是一个必需值。
    • 只允许 .spec 下的 JSONPath 和点表示法。
    • 如果自定义资源中 specReplicasPath 下没有值,则 /scale 子资源在 GET 时将返回错误。
  • statusReplicasPath 定义了自定义资源中与 scale.status.replicas 对应的 JSONPath。

    • 它是一个必需值。
    • 只允许 .status 下的 JSONPath 和点表示法。
    • 如果自定义资源中 statusReplicasPath 下没有值,则 /scale 子资源中的状态副本值将默认为 0。
  • labelSelectorPath 定义了自定义资源中与 Scale.Status.Selector 对应的 JSONPath。

    • 它是一个可选值。
    • 必须设置它才能与 HPA 和 VPA 配合使用。
    • 只允许 .status.spec 下的 JSONPath 和点表示法。
    • 如果自定义资源中 labelSelectorPath 下没有值,则 /scale 子资源中的状态选择器值将默认为空字符串。
    • 此 JSON 路径指向的字段必须是一个字符串字段(而不是复杂的选择器结构),其中包含字符串形式的序列化标签选择器。

在以下示例中,状态和扩缩子资源都已启用。

将 CustomResourceDefinition 保存到 resourcedefinition.yaml

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: crontabs.stable.example.com
spec:
  group: stable.example.com
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                cronSpec:
                  type: string
                image:
                  type: string
                replicas:
                  type: integer
            status:
              type: object
              properties:
                replicas:
                  type: integer
                labelSelector:
                  type: string
      # subresources describes the subresources for custom resources.
      subresources:
        # status enables the status subresource.
        status: {}
        # scale enables the scale subresource.
        scale:
          # specReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Spec.Replicas.
          specReplicasPath: .spec.replicas
          # statusReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Replicas.
          statusReplicasPath: .status.replicas
          # labelSelectorPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Selector.
          labelSelectorPath: .status.labelSelector
  scope: Namespaced
  names:
    plural: crontabs
    singular: crontab
    kind: CronTab
    shortNames:
    - ct

并创建它

kubectl apply -f resourcedefinition.yaml

创建 CustomResourceDefinition 对象后,您可以创建自定义对象。

如果你将以下 YAML 保存到 my-crontab.yaml

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  cronSpec: "* * * * */5"
  image: my-awesome-cron-image
  replicas: 3

并创建它

kubectl apply -f my-crontab.yaml

然后,在以下位置创建新的命名空间 RESTful API 端点

/apis/stable.example.com/v1/namespaces/*/crontabs/status

/apis/stable.example.com/v1/namespaces/*/crontabs/scale

可以使用 kubectl scale 命令扩缩自定义资源。例如,以下命令将上面创建的自定义资源的 .spec.replicas 设置为 5

kubectl scale --replicas=5 crontabs/my-new-cron-object
crontabs "my-new-cron-object" scaled

kubectl get crontabs my-new-cron-object -o jsonpath='{.spec.replicas}'
5

您可以使用 PodDisruptionBudget 来保护已启用扩缩子资源的自定义资源。

类别

类别是自定义资源所属的分组资源列表(例如 all)。您可以使用 kubectl get 列出属于该类别的资源。

以下示例在 CustomResourceDefinition 的类别列表中添加了 all,并演示了如何使用 kubectl get all 输出自定义资源。

将以下 CustomResourceDefinition 保存到 resourcedefinition.yaml

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: crontabs.stable.example.com
spec:
  group: stable.example.com
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                cronSpec:
                  type: string
                image:
                  type: string
                replicas:
                  type: integer
  scope: Namespaced
  names:
    plural: crontabs
    singular: crontab
    kind: CronTab
    shortNames:
    - ct
    # categories is a list of grouped resources the custom resource belongs to.
    categories:
    - all

并创建它

kubectl apply -f resourcedefinition.yaml

创建 CustomResourceDefinition 对象后,您可以创建自定义对象。

将以下 YAML 保存到 my-crontab.yaml

apiVersion: "stable.example.com/v1"
kind: CronTab
metadata:
  name: my-new-cron-object
spec:
  cronSpec: "* * * * */5"
  image: my-awesome-cron-image

并创建它

kubectl apply -f my-crontab.yaml

您可以在使用 kubectl get 时指定类别

kubectl get all

它将包含种类为 CronTab 的自定义资源

NAME                          AGE
crontabs/my-new-cron-object   3s

下一步

上次修改时间:2025 年 5 月 12 日下午 2:52 (PST):将 yaml 示例标记为可获取语法高亮显示 (365e6495ea)