Appendix B. Custom Resource Validation

When adding a new API, the Operator SDK generates a skeleton custom resource definition. This skeleton is usable as is; no further changes or additions need to be made to create custom resources.

The skeleton CRD achieves this flexibility by simply defining the spec and status sections, representing the user input and custom resource state, respectively, as open-ended objects:

spec:
    type: object
status:
    type: object

The drawback to this approach is that Kubernetes isn’t able to validate any of the data in either of these fields. Since Kubernetes doesn’t know what values should or should not be allowed, as long as the manifest parses, the values are allowed.

To solve this problem, CRDs include support for the OpenAPI Specification to describe the validation constraints of each of its fields. You’ll need to manually add this validation to the CRD to describe the allowed values for both the spec and status sections.

You’ll make two primary changes to the spec section of the CRD:

  • Add a properties map. For each of the attributes that may be specified for custom resources of this type, add an entry to this map along with information on the parameter’s type and allowed values.

  • Optionally, you can add a required field listing the properties whose presence Kubernetes should enforce. Add the name of each required property as an entry in this list. If you omit any of these properties during resource creation, Kubernetes will reject the resource.

You can also flesh out the status section with property information following the same conventions as for spec; however, there is no need to add a required field.

Warning

In both cases, the existing line type: object remains; you insert the new additions at the same level as this “type” declaration.

You can find both the spec and status fields in the following section of the CRD:

spec -> validation -> openAPIV3Schema -> properties

As an example, the additions to the VisitorsApp CRD are as follows:

spec:
    type: object
    properties:
        size:
            type: integer
        title:
            type: string
    required:
    - size
status:
    type: object
    properties:
        backendImage:
            type: string
        frontendImage:
            type: string

This snippet is only an example of what you can accomplish using OpenAPI validation. You can find detailed information on creating custom resource definitions in the Kubernetes documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset