You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Kubernetes CRD指定OpenAPI校验规则

Hey there! I see you're working on a Kubernetes controller with the Go client, and you've already got openapi-gen generating specs using the +k8s:openapi-gen=true annotation. Adding validation rules like max length or regex patterns is totally doable—let me walk you through the most straightforward ways to make this happen.

The easiest way to tie validation rules directly to your Go types (and have them propagate to both your OpenAPI spec and CRD) is using Kubebuilder validation annotations. These annotations are parsed by tools like controller-gen to auto-generate CRD validation rules, and openapi-gen will pick them up too to include in your OpenAPI spec.

Here's how to add them to your types.go—I'll extend your existing code with example fields and rules:

package v1

import (
    meta "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +genclient
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status

// MyResource is the Schema for myresources API
type MyResource struct {
    meta.TypeMeta   `json:",inline"`
    meta.ObjectMeta `json:"metadata,omitempty"`

    Spec   MyResourceSpec   `json:"spec,omitempty"`
    Status MyResourceStatus `json:"status,omitempty"`
}

// MyResourceSpec defines the desired state of MyResource
type MyResourceSpec struct {
    // Enforce max length of 128 characters and alphanumeric/hyphen/underscore pattern
    // +kubebuilder:validation:MaxLength=128
    // +kubebuilder:validation:Pattern=`^[A-Za-z0-9-_]+$`
    DisplayName string `json:"displayName"`

    // Require at least 1 tag, no more than 10 total
    // +kubebuilder:validation:MinItems=1
    // +kubebuilder:validation:MaxItems=10
    Tags []string `json:"tags,omitempty"`
}

// MyResourceStatus defines the observed state of MyResource
type MyResourceStatus struct {
    // Restrict phase to predefined valid values
    // +kubebuilder:validation:Enum=Ready;Pending;Error
    Phase string `json:"phase,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// MyResourceList contains a list of MyResource
type MyResourceList struct {
    meta.TypeMeta `json:",inline"`
    meta.ListMeta `json:"metadata,omitempty"`
    Items         []MyResource `json:"items"`
}

Once you've added these annotations:

  • Run controller-gen crd paths=./... output:crd:artifacts:config=config/crd/bases to generate an updated CRD with validation rules baked in.
  • Re-run your openapi-gen command—your spec will now include the maxLength, pattern, minItems, etc., constraints for each field.

When you apply this CRD to your cluster, the Kubernetes API server will automatically validate any create/update requests against these rules before they reach your controller.

Option 2: Manual CRD Validation (No Kubebuilder)

If you're not using Kubebuilder, you can manually define validation rules directly in your CRD's spec.validation.openAPIV3Schema section. For example:

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: myresources.example.com
spec:
  group: example.com
  versions:
    - name: v1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                displayName:
                  type: string
                  maxLength: 128
                  pattern: "^[A-Za-z0-9-_]+$"
                tags:
                  type: array
                  items:
                    type: string
                  minItems: 1
                  maxItems: 10
              required:
                - displayName

This achieves the same API server-level validation, but you'll have to keep the CRD in sync with your Go types manually (which is less maintainable long-term).

Option 3: Validating Admission Webhooks (For Complex Logic)

If you need more advanced validation (like cross-resource checks, dynamic rules based on cluster state, or custom business logic), you can build a Validating Admission Webhook. This is a separate service that the API server calls before persisting any resource changes.

While this is more powerful, it requires deploying the webhook service, managing TLS certificates, and writing the validation logic—so it's overkill for simple rules like max length or regex.

Key Notes

  • The annotations work with openapi-gen because they're part of the Kubernetes API machinery's metadata for type validation.
  • All validation done via CRD rules or admission webhooks happens at the API server level, so invalid requests are rejected early, saving your controller from having to handle bad data.

内容的提问来源于stack exchange,提问作者Calin Don

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:07:24