【问题标题】:kubernetes custom resource definition required fieldkubernetes 自定义资源定义必填字段
【发布时间】:2018-11-19 03:56:48
【问题描述】:

我正在尝试编写一个 kubernetes crd 验证模式。我有一个结构数组 (vc),其中一个字段是必需的(name 字段)。

我尝试查看各种示例,但当name 不存在时它不会产生错误。有什么建议吗?

vc:
  type: array
  items:
    type: object
    properties:
      name:
        type: string
      address:
        type: string
    required:
    - name

【问题讨论】:

  • CRD 的其他验证是否适合您?我的意思是,其他必填字段?还有,你的 Kubernetes 版本是什么?

标签: kubernetes kubernetes-custom-resources


【解决方案1】:

如果您使用的是 v1.8,则需要启用 CustomResourceValidation 功能门才能使用验证功能。这可以通过在 kube-apiserver 上使用以下标志来完成:

--feature-gates=CustomResourceValidation=true

这是一个工作示例(我在 v1.12 上对此进行了测试,但这应该也适用于早期版本):

CRD:

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: foos.stable.example.com
spec:
  group: stable.example.com
  versions:
    - name: v1
      served: true
      storage: true
  version: v1
  scope: Namespaced
  names:
    plural: foos
    singular: foo
    kind: Foo
  validation:
    openAPIV3Schema:
      properties:
        spec:
          properties:
            vc:
              type: array
              items:
                type: object
                properties:
                  name:
                    type: string
                  address:
                    type: string
                required:
                - name

自定义资源:

apiVersion: "stable.example.com/v1"
kind: Foo
metadata:
  name: new-foo
spec:
  vc:
  - address: "bar"
  1. 创建 CRD。

kubectl create -f crd.yaml customresourcedefinition.apiextensions.k8s.io/foos.stable.example.com created

  1. 获取 CRD 并检查输出中是否存在验证字段。如果没有,您可能没有打开功能门。

kubectl get crd foos.stable.example.com -oyaml

  1. 尝试创建自定义资源。这应该失败:

kubectl create -f cr-validation.yaml

The Foo "new-foo" is invalid: []: Invalid value: map[string]interface {}{"metadata":map[string]interface {}{"creationTimestamp":"2018-11-18T19:45:23Z", "generation":1, "uid":"7d7f8f0b-eb6a-11e8-b861-54e1ad9de0be", "name":"new-foo", "namespace":"default"}, "spec":map[string]interface {}{"vc":[]interface {}{map[string]interface {}{"address":"bar"}}}, "apiVersion":"stable.example.com/v1", "kind":"Foo"}: validation failure list: spec.vc.name in body is required

【讨论】:

  • vc 下,如果必须在自定义资源对象中设置nameaddress,它会是什么样子?像这样: ? ``` vc: - 名称:“某个名字” - 地址:“酒吧” ```
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-04
  • 1970-01-01
  • 2016-09-07
  • 2016-06-14
相关资源
最近更新 更多