Extend the Kubernetes API with CustomResourceDefinitions

This page shows how to install a custom resource into the Kubernetes API by creating a CustomResourceDefinition.

Before you begin

You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. If you do not already have a cluster, you can create one by using Minikube, or you can use one of these Kubernetes playgrounds:

To check the version, enter kubectl version.

  • Make sure your Kubernetes cluster has a master version of 1.16.0 or higher to use apiextensions.k8s.io/v1, or 1.7.0 or higher for apiextensions.k8s.io/v1beta1.

  • Read about custom resources.

Create a CustomResourceDefinition

When you create a new CustomResourceDefinition (CRD), the Kubernetes API Server creates a new RESTful resource path for each version you specify. The CRD can be either namespaced or cluster-scoped, as specified in the CRD’s scope field. As with existing built-in objects, deleting a namespace deletes all custom objects in that namespace. CustomResourceDefinitions themselves are non-namespaced and are available to all namespaces.

For example, if you save the following CustomResourceDefinition to resourcedefinition.yaml:

  1. apiVersion: apiextensions.k8s.io/v1
  2. kind: CustomResourceDefinition
  3. metadata:
  4. # name must match the spec fields below, and be in the form: <plural>.<group>
  5. name: crontabs.stable.example.com
  6. spec:
  7. # group name to use for REST API: /apis/<group>/<version>
  8. group: stable.example.com
  9. # list of versions supported by this CustomResourceDefinition
  10. versions:
  11. - name: v1
  12. # Each version can be enabled/disabled by Served flag.
  13. served: true
  14. # One and only one version must be marked as the storage version.
  15. storage: true
  16. schema:
  17. openAPIV3Schema:
  18. type: object
  19. properties:
  20. spec:
  21. type: object
  22. properties:
  23. cronSpec:
  24. type: string
  25. image:
  26. type: string
  27. replicas:
  28. type: integer
  29. # either Namespaced or Cluster
  30. scope: Namespaced
  31. names:
  32. # plural name to be used in the URL: /apis/<group>/<version>/<plural>
  33. plural: crontabs
  34. # singular name to be used as an alias on the CLI and for display
  35. singular: crontab
  36. # kind is normally the CamelCased singular type. Your resource manifests use this.
  37. kind: CronTab
  38. # shortNames allow shorter string to match your resource on the CLI
  39. shortNames:
  40. - ct
  1. # Deprecated in v1.16 in favor of apiextensions.k8s.io/v1
  2. apiVersion: apiextensions.k8s.io/v1beta1
  3. kind: CustomResourceDefinition
  4. metadata:
  5. # name must match the spec fields below, and be in the form: <plural>.<group>
  6. name: crontabs.stable.example.com
  7. spec:
  8. # group name to use for REST API: /apis/<group>/<version>
  9. group: stable.example.com
  10. # list of versions supported by this CustomResourceDefinition
  11. versions:
  12. - name: v1
  13. # Each version can be enabled/disabled by Served flag.
  14. served: true
  15. # One and only one version must be marked as the storage version.
  16. storage: true
  17. # either Namespaced or Cluster
  18. scope: Namespaced
  19. names:
  20. # plural name to be used in the URL: /apis/<group>/<version>/<plural>
  21. plural: crontabs
  22. # singular name to be used as an alias on the CLI and for display
  23. singular: crontab
  24. # kind is normally the CamelCased singular type. Your resource manifests use this.
  25. kind: CronTab
  26. # shortNames allow shorter string to match your resource on the CLI
  27. shortNames:
  28. - ct
  29. preserveUnknownFields: false
  30. validation:
  31. openAPIV3Schema:
  32. type: object
  33. properties:
  34. spec:
  35. type: object
  36. properties:
  37. cronSpec:
  38. type: string
  39. image:
  40. type: string
  41. replicas:
  42. type: integer

And create it:

  1. kubectl apply -f resourcedefinition.yaml

Then a new namespaced RESTful API endpoint is created at:

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

This endpoint URL can then be used to create and manage custom objects. The kind of these objects will be CronTab from the spec of the CustomResourceDefinition object you created above.

It might take a few seconds for the endpoint to be created. You can watch the Established condition of your CustomResourceDefinition to be true or watch the discovery information of the API server for your resource to show up.

Create custom objects

After the CustomResourceDefinition object has been created, you can create custom objects. Custom objects can contain custom fields. These fields can contain arbitrary JSON. In the following example, the cronSpec and image custom fields are set in a custom object of kind CronTab. The kind CronTab comes from the spec of the CustomResourceDefinition object you created above.

If you save the following YAML to my-crontab.yaml:

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

and create it:

  1. kubectl apply -f my-crontab.yaml

You can then manage your CronTab objects using kubectl. For example:

  1. kubectl get crontab

Should print a list like this:

  1. NAME AGE
  2. my-new-cron-object 6s

Resource names are not case-sensitive when using kubectl, and you can use either the singular or plural forms defined in the CRD, as well as any short names.

You can also view the raw YAML data:

  1. kubectl get ct -o yaml

You should see that it contains the custom cronSpec and image fields from the yaml you used to create it:

  1. apiVersion: v1
  2. kind: List
  3. items:
  4. - apiVersion: stable.example.com/v1
  5. kind: CronTab
  6. metadata:
  7. creationTimestamp: 2017-05-31T12:56:35Z
  8. generation: 1
  9. name: my-new-cron-object
  10. namespace: default
  11. resourceVersion: "285"
  12. uid: 9423255b-4600-11e7-af6a-28d2447dc82b
  13. spec:
  14. cronSpec: '* * * * */5'
  15. image: my-awesome-cron-image
  16. metadata:
  17. resourceVersion: ""

Delete a CustomResourceDefinition

When you delete a CustomResourceDefinition, the server will uninstall the RESTful API endpoint and delete all custom objects stored in it.

  1. kubectl delete -f resourcedefinition.yaml
  2. kubectl get crontabs
  1. 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)

If you later recreate the same CustomResourceDefinition, it will start out empty.

Specifying a structural schema

FEATURE STATE: Kubernetes 1.16 stable

This feature is stable, meaning:

  • The version name is vX where X is an integer.
  • Stable versions of features will appear in released software for many subsequent versions.

CustomResources traditionally store arbitrary JSON (next to apiVersion, kind and metadata, which is validated by the API server implicitly). With OpenAPI v3.0 validation a schema can be specified, which is validated during creation and updates, compare below for details and limits of such a schema.

With apiextensions.k8s.io/v1 the definition of a structural schema is mandatory for CustomResourceDefinitions, while in v1beta1 this is still optional.

A structural schema is an OpenAPI v3.0 validation schema which:

  1. specifies a non-empty type (via type in OpenAPI) for the root, for each specified field of an object node (via properties or additionalProperties in OpenAPI) and for each item in an array node (via items in OpenAPI), with the exception of:
    • a node with x-kubernetes-int-or-string: true
    • a node with x-kubernetes-preserve-unknown-fields: true
  2. for each field in an object and each item in an array which is specified within any of allOf, anyOf, oneOf or not, the schema also specifies the field/item outside of those logical junctors (compare example 1 and 2).
  3. does not set description, type, default, additionalProperties, nullable within an allOf, anyOf, oneOf or not, with the exception of the two pattern for x-kubernetes-int-or-string: true (see below).
  4. if metadata is specified, then only restrictions on metadata.name and metadata.generateName are allowed.

Non-Structural Example 1:

  1. allOf:
  2. - properties:
  3. foo:
  4. ...

conflicts with rule 2. The following would be correct:

  1. properties:
  2. foo:
  3. ...
  4. allOf:
  5. - properties:
  6. foo:
  7. ...

Non-Structural Example 2:

  1. allOf:
  2. - items:
  3. properties:
  4. foo:
  5. ...

conflicts with rule 2. The following would be correct:

  1. items:
  2. properties:
  3. foo:
  4. ...
  5. allOf:
  6. - items:
  7. properties:
  8. foo:
  9. ...

Non-Structural Example 3:

  1. properties:
  2. foo:
  3. pattern: "abc"
  4. metadata:
  5. type: object
  6. properties:
  7. name:
  8. type: string
  9. pattern: "^a"
  10. finalizers:
  11. type: array
  12. items:
  13. type: string
  14. pattern: "my-finalizer"
  15. anyOf:
  16. - properties:
  17. bar:
  18. type: integer
  19. minimum: 42
  20. required: ["bar"]
  21. description: "foo bar object"

is not a structural schema because of the following violations:

  • the type at the root is missing (rule 1).
  • the type of foo is missing (rule 1).
  • bar inside of anyOf is not specified outside (rule 2).
  • bar’s type is within anyOf (rule 3).
  • the description is set within anyOf (rule 3).
  • metadata.finalizer might not be restricted (rule 4).

In contrast, the following, corresponding schema is structural:

  1. type: object
  2. description: "foo bar object"
  3. properties:
  4. foo:
  5. type: string
  6. pattern: "abc"
  7. bar:
  8. type: integer
  9. metadata:
  10. type: object
  11. properties:
  12. name:
  13. type: string
  14. pattern: "^a"
  15. anyOf:
  16. - properties:
  17. bar:
  18. minimum: 42
  19. required: ["bar"]

Violations of the structural schema rules are reported in the NonStructural condition in the CustomResourceDefinition.

Structural schemas are a requirement for apiextensions.k8s.io/v1, and disables the following features for apiextensions.k8s.io/v1beta1:

Pruning versus preserving unknown fields

FEATURE STATE: Kubernetes 1.16 stable

This feature is stable, meaning:

  • The version name is vX where X is an integer.
  • Stable versions of features will appear in released software for many subsequent versions.

CustomResourceDefinitions traditionally store any (possibly validated) JSON as is in etcd. This means that unspecified fields (if there is a OpenAPI v3.0 validation schema at all) are persisted. This is in contrast to native Kubernetes resources such as a pod where unknown fields are dropped before being persisted to etcd. We call this “pruning” of unknown fields.

For CustomResourceDefinitions created in apiextensions.k8s.io/v1, structural OpenAPI v3 validation schemas are required and pruning is enabled and cannot be disabled (note that CRDs converted from apiextensions.k8s.io/v1beta1 to apiextensions.k8s.io/v1 might lack structural schemas, and spec.preserveUnknownFields might be true).

For CustomResourceDefinitions created in apiextensions.k8s.io/v1beta1, if a structural OpenAPI v3 validation schema is defined (either in the global spec.validation.openAPIV3Schema in apiextensions.k8s.io/v1beta1 or for each version) in a CustomResourceDefinition, pruning can be enabled by setting spec.preserveUnknownFields to false.

If pruning is enabled, unspecified fields in CustomResources on creation and on update are dropped.

Compare the CustomResourceDefinition crontabs.stable.example.com above. It has pruning enabled (both in apiextensions.k8s.io/v1 and apiextensions.k8s.io/v1beta1). Hence, if you save the following YAML to my-crontab.yaml:

  1. apiVersion: "stable.example.com/v1"
  2. kind: CronTab
  3. metadata:
  4. name: my-new-cron-object
  5. spec:
  6. cronSpec: "* * * * */5"
  7. image: my-awesome-cron-image
  8. someRandomField: 42

and create it:

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

you should get:

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

The field someRandomField has been pruned.

Note that the kubectl create call uses --validate=false to skip client-side validation. Because the OpenAPI validation schemas are also published to kubectl, it will also check for unknown fields and reject those objects long before they are sent to the API server.

Controlling pruning

If pruning is enabled (enforced in apiextensions.k8s.io/v1, or as opt-in via spec.preserveUnknownField: false in apiextensions.k8s.io/v1beta1) in the CustomResourceDefinition, all unspecified fields in custom resources of that type and in all versions are pruned. It is possible though to opt-out of that for JSON sub-trees via x-kubernetes-preserve-unknown-fields: true in the structural OpenAPI v3 validation schema:

  1. type: object
  2. properties:
  3. json:
  4. x-kubernetes-preserve-unknown-fields: true

The field json can store any JSON value, without anything being pruned.

It is possible to partially specify the permitted JSON, e.g.:

  1. type: object
  2. properties:
  3. json:
  4. x-kubernetes-preserve-unknown-fields: true
  5. type: object
  6. description: this is arbitrary JSON

With this only object type values are allowed.

Pruning is enabled again for each specified property (or additionalProperties):

  1. type: object
  2. properties:
  3. json:
  4. x-kubernetes-preserve-unknown-fields: true
  5. type: object
  6. properties:
  7. spec:
  8. type: object
  9. properties:
  10. foo:
  11. type: string
  12. bar:
  13. type: string

With this, the value:

  1. json:
  2. spec:
  3. foo: abc
  4. bar: def
  5. something: x
  6. status:
  7. something: x

is pruned to:

  1. json:
  2. spec:
  3. foo: abc
  4. bar: def
  5. status:
  6. something: x

This means that the something field in the specified spec object is pruned, but everything outside is not.

IntOrString

Nodes in a schema with x-kubernetes-int-or-string: true are excluded from rule 1, such that the following is structural:

  1. type: object
  2. properties:
  3. foo:
  4. x-kubernetes-int-or-string: true

Also those nodes are partially excluded from rule 3 in the sense that the following two patterns are allowed (exactly those, without variations in order to additional fields):

  1. x-kubernetes-int-or-string: true
  2. anyOf:
  3. - type: integer
  4. - type: string
  5. ...

and

  1. x-kubernetes-int-or-string: true
  2. allOf:
  3. - anyOf:
  4. - type: integer
  5. - type: string
  6. - ... # zero or more
  7. ...

With one of those specification, both an integer and a string validate.

In Validation Schema Publishing, x-kubernetes-int-or-string: true is unfolded to one of the two patterns shown above.

RawExtension

RawExtensions (as in runtime.RawExtension defined in k8s.io/apimachinery) holds complete Kubernetes objects, i.e. with apiVersion and kind fields.

It is possible to specify those embedded objects (both completely without constraints or partially specified) by setting x-kubernetes-embedded-resource: true. For example:

  1. type: object
  2. properties:
  3. foo:
  4. x-kubernetes-embedded-resource: true
  5. x-kubernetes-preserve-unknown-fields: true

Here, the field foo holds a complete object, e.g.:

  1. foo:
  2. apiVersion: v1
  3. kind: Pod
  4. spec:
  5. ...

Because x-kubernetes-preserve-unknown-fields: true is specified alongside, nothing is pruned. The use of x-kubernetes-preserve-unknown-fields: true is optional though.

With x-kubernetes-embedded-resource: true, the apiVersion, kind and metadata are implicitly specified and validated.

Serving multiple versions of a CRD

See Custom resource definition versioning for more information about serving multiple versions of your CustomResourceDefinition and migrating your objects from one version to another.

Advanced topics

Finalizers

Finalizers allow controllers to implement asynchronous pre-delete hooks. Custom objects support finalizers just like built-in objects.

You can add a finalizer to a custom object like this:

  1. apiVersion: "stable.example.com/v1"
  2. kind: CronTab
  3. metadata:
  4. finalizers:
  5. - finalizer.stable.example.com

Finalizers are arbitrary string values, that when present ensure that a hard delete of a resource is not possible while they exist.

The first delete request on an object with finalizers sets a value for the metadata.deletionTimestamp field but does not delete it. Once this value is set, entries in the finalizer list can only be removed.

When the metadata.deletionTimestamp field is set, controllers watching the object execute any finalizers they handle, by polling update requests for that object. When all finalizers have been executed, the resource is deleted.

The value of metadata.deletionGracePeriodSeconds controls the interval between polling updates.

It is the responsibility of each controller to remove its finalizer from the list.

Kubernetes only finally deletes the object if the list of finalizers is empty, meaning all finalizers have been executed.

Validation

FEATURE STATE: Kubernetes 1.16 stable

This feature is stable, meaning:

  • The version name is vX where X is an integer.
  • Stable versions of features will appear in released software for many subsequent versions.

Validation of custom objects is possible via OpenAPI v3 schemas or validatingadmissionwebhook. In apiextensions.k8s.io/v1 schemas are required, in apiextensions.k8s.io/v1beta1 they are optional.

Additionally, the following restrictions are applied to the schema:

  • These fields cannot be set:
    • definitions,
    • dependencies,
    • deprecated,
    • discriminator,
    • id,
    • patternProperties,
    • readOnly,
    • writeOnly,
    • xml,
    • $ref.
  • The field uniqueItems cannot be set to true.
  • The field additionalProperties cannot be set to false.
  • The field additionalProperties is mutually exclusive with properties.

These fields can only be set with specific features enabled:

  • default: can be set for apiextensions.k8s.io/v1 CustomResourceDefinitions. Defaulting is in GA since 1.17 (beta since 1.16 with the CustomResourceDefaulting feature gate to be enabled, which is the case automatically for many clusters for beta features). Compare Validation Schema Defaulting.

Note: compare with structural schemas for further restriction required for certain CustomResourceDefinition features.

The schema is defined in the CustomResourceDefinition. In the following example, the CustomResourceDefinition applies the following validations on the custom object:

  • spec.cronSpec must be a string and must be of the form described by the regular expression.
  • spec.replicas must be an integer and must have a minimum value of 1 and a maximum value of 10.

Save the CustomResourceDefinition to resourcedefinition.yaml:

  1. apiVersion: apiextensions.k8s.io/v1
  2. kind: CustomResourceDefinition
  3. metadata:
  4. name: crontabs.stable.example.com
  5. spec:
  6. group: stable.example.com
  7. versions:
  8. - name: v1
  9. served: true
  10. storage: true
  11. schema:
  12. # openAPIV3Schema is the schema for validating custom objects.
  13. openAPIV3Schema:
  14. type: object
  15. properties:
  16. spec:
  17. type: object
  18. properties:
  19. cronSpec:
  20. type: string
  21. pattern: '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
  22. replicas:
  23. type: integer
  24. minimum: 1
  25. maximum: 10
  26. scope: Namespaced
  27. names:
  28. plural: crontabs
  29. singular: crontab
  30. kind: CronTab
  31. shortNames:
  32. - ct
  1. # Deprecated in v1.16 in favor of apiextensions.k8s.io/v1
  2. apiVersion: apiextensions.k8s.io/v1beta1
  3. kind: CustomResourceDefinition
  4. metadata:
  5. name: crontabs.stable.example.com
  6. spec:
  7. group: stable.example.com
  8. versions:
  9. - name: v1
  10. served: true
  11. storage: true
  12. version: v1
  13. scope: Namespaced
  14. names:
  15. plural: crontabs
  16. singular: crontab
  17. kind: CronTab
  18. shortNames:
  19. - ct
  20. validation:
  21. # openAPIV3Schema is the schema for validating custom objects.
  22. openAPIV3Schema:
  23. type: object
  24. properties:
  25. spec:
  26. type: object
  27. properties:
  28. cronSpec:
  29. type: string
  30. pattern: '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
  31. replicas:
  32. type: integer
  33. minimum: 1
  34. maximum: 10

And create it:

  1. kubectl apply -f resourcedefinition.yaml

A request to create a custom object of kind CronTab will be rejected if there are invalid values in its fields. In the following example, the custom object contains fields with invalid values:

  • spec.cronSpec does not match the regular expression.
  • spec.replicas is greater than 10.

If you save the following YAML to my-crontab.yaml:

  1. apiVersion: "stable.example.com/v1"
  2. kind: CronTab
  3. metadata:
  4. name: my-new-cron-object
  5. spec:
  6. cronSpec: "* * * *"
  7. image: my-awesome-cron-image
  8. replicas: 15

and create it:

  1. kubectl apply -f my-crontab.yaml

you will get an error:

  1. 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}}:
  2. validation failure list:
  3. spec.cronSpec in body should match '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
  4. spec.replicas in body should be less than or equal to 10

If the fields contain valid values, the object creation request is accepted.

Save the following YAML to my-crontab.yaml:

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

And create it:

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

Defaulting

FEATURE STATE: Kubernetes 1.17 stable

This feature is stable, meaning:

  • The version name is vX where X is an integer.
  • Stable versions of features will appear in released software for many subsequent versions.

Note: To use defaulting, your CustomResourceDefinition must use API version apiextensions.k8s.io/v1.

Defaulting allows to specify default values in the OpenAPI v3 validation schema:

  1. apiVersion: apiextensions.k8s.io/v1
  2. kind: CustomResourceDefinition
  3. metadata:
  4. name: crontabs.stable.example.com
  5. spec:
  6. group: stable.example.com
  7. versions:
  8. - name: v1
  9. served: true
  10. storage: true
  11. schema:
  12. # openAPIV3Schema is the schema for validating custom objects.
  13. openAPIV3Schema:
  14. type: object
  15. properties:
  16. spec:
  17. type: object
  18. properties:
  19. cronSpec:
  20. type: string
  21. pattern: '^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'
  22. default: "5 0 * * *"
  23. image:
  24. type: string
  25. replicas:
  26. type: integer
  27. minimum: 1
  28. maximum: 10
  29. default: 1
  30. scope: Namespaced
  31. names:
  32. plural: crontabs
  33. singular: crontab
  34. kind: CronTab
  35. shortNames:
  36. - ct

With this both cronSpec and replicas are defaulted:

  1. apiVersion: "stable.example.com/v1"
  2. kind: CronTab
  3. metadata:
  4. name: my-new-cron-object
  5. spec:
  6. image: my-awesome-cron-image

leads to

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

Note that defaulting happens on the object

  • in the request to the API server using the request version defaults,
  • when reading from etcd using the storage version defaults,
  • after mutating admission plugins with non-empty patches using the admission webhook object version defaults.

Defaults applied when reading data from etcd are not automatically written back to etcd. An update request via the API is required to persist those defaults back into etcd.

Default values must be pruned (with the exception of defaults for metadata fields) and must validate against a provided schema.

Default values for metadata fields of x-kubernetes-embedded-resources: true nodes (or parts of a default value covering metadata) are not pruned during CustomResourceDefinition creation, but through the pruning step during handling of requests.

Publish Validation Schema in OpenAPI v2

FEATURE STATE: Kubernetes 1.16 stable

This feature is stable, meaning:

  • The version name is vX where X is an integer.
  • Stable versions of features will appear in released software for many subsequent versions.

Note: OpenAPI v2 Publishing is available as beta since 1.15, and as alpha since 1.14. The CustomResourcePublishOpenAPI feature must be enabled, which is the case automatically for many clusters for beta features. Please refer to the feature gate documentation for more information.

With the OpenAPI v2 Publishing feature enabled, CustomResourceDefinition OpenAPI v3 validation schemas which are structural and enable pruning (opt-in in v1beta1, enabled by default in v1) are published as part of the OpenAPI v2 spec from Kubernetes API server.

kubectl consumes the published schema to perform client-side validation (kubectl create and kubectl apply), schema explanation (kubectl explain) on custom resources. The published schema can be consumed for other purposes as well, like client generation or documentation.

The OpenAPI v3 validation schema is converted to OpenAPI v2 schema, and show up in definitions and paths fields in the OpenAPI v2 spec. The following modifications are applied during the conversion to keep backwards compatibility with kubectl in previous 1.13 version. These modifications prevent kubectl from being over-strict and rejecting valid OpenAPI schemas that it doesn’t understand. The conversion won’t modify the validation schema defined in CRD, and therefore won’t affect validation in the API server.

  1. The following fields are removed as they aren’t supported by OpenAPI v2 (in future versions OpenAPI v3 will be used without these restrictions)
    • The fields allOf, anyOf, oneOf and not are removed
  2. If nullable: true is set, we drop type, nullable, items and properties because OpenAPI v2 is not able to express nullable. To avoid kubectl to reject good objects, this is necessary.

Additional printer columns

Starting with Kubernetes 1.11, kubectl uses server-side printing. The server decides which columns are shown by the kubectl get command. You can customize these columns using a CustomResourceDefinition. The following example adds the Spec, Replicas, and Age columns.

  1. Save the CustomResourceDefinition to resourcedefinition.yaml.
  1. apiVersion: apiextensions.k8s.io/v1
  2. kind: CustomResourceDefinition
  3. metadata:
  4. name: crontabs.stable.example.com
  5. spec:
  6. group: stable.example.com
  7. scope: Namespaced
  8. names:
  9. plural: crontabs
  10. singular: crontab
  11. kind: CronTab
  12. shortNames:
  13. - ct
  14. versions:
  15. - name: v1
  16. served: true
  17. storage: true
  18. schema:
  19. openAPIV3Schema:
  20. type: object
  21. properties:
  22. spec:
  23. type: object
  24. properties:
  25. cronSpec:
  26. type: string
  27. image:
  28. type: string
  29. replicas:
  30. type: integer
  31. additionalPrinterColumns:
  32. - name: Spec
  33. type: string
  34. description: The cron spec defining the interval a CronJob is run
  35. jsonPath: .spec.cronSpec
  36. - name: Replicas
  37. type: integer
  38. description: The number of jobs launched by the CronJob
  39. jsonPath: .spec.replicas
  40. - name: Age
  41. type: date
  42. jsonPath: .metadata.creationTimestamp
  1. # Deprecated in v1.16 in favor of apiextensions.k8s.io/v1
  2. apiVersion: apiextensions.k8s.io/v1beta1
  3. kind: CustomResourceDefinition
  4. metadata:
  5. name: crontabs.stable.example.com
  6. spec:
  7. group: stable.example.com
  8. version: v1
  9. scope: Namespaced
  10. names:
  11. plural: crontabs
  12. singular: crontab
  13. kind: CronTab
  14. shortNames:
  15. - ct
  16. validation:
  17. openAPIV3Schema:
  18. type: object
  19. properties:
  20. spec:
  21. type: object
  22. properties:
  23. cronSpec:
  24. type: string
  25. image:
  26. type: string
  27. replicas:
  28. type: integer
  29. additionalPrinterColumns:
  30. - name: Spec
  31. type: string
  32. description: The cron spec defining the interval a CronJob is run
  33. JSONPath: .spec.cronSpec
  34. - name: Replicas
  35. type: integer
  36. description: The number of jobs launched by the CronJob
  37. JSONPath: .spec.replicas
  38. - name: Age
  39. type: date
  40. JSONPath: .metadata.creationTimestamp
  1. Create the CustomResourceDefinition:

    1. kubectl apply -f resourcedefinition.yaml
  2. Create an instance using the my-crontab.yaml from the previous section.

  3. Invoke the server-side printing:

    1. kubectl get crontab my-new-cron-object

    Notice the NAME, SPEC, REPLICAS, and AGE columns in the output:

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

The NAME column is implicit and does not need to be defined in the CustomResourceDefinition.

Priority

Each column includes a priority field for each column. Currently, the priority differentiates between columns shown in standard view or wide view (using the -o wide flag).

  • Columns with priority 0 are shown in standard view.
  • Columns with priority greater than 0 are shown only in wide view.

Type

A column’s type field can be any of the following (compare OpenAPI v3 data types):

  • integer – non-floating-point numbers
  • number – floating point numbers
  • string – strings
  • boolean – true or false
  • date – rendered differentially as time since this timestamp.

If the value inside a CustomResource does not match the type specified for the column, the value is omitted. Use CustomResource validation to ensure that the value types are correct.

Format

A column’s format field can be any of the following:

  • int32
  • int64
  • float
  • double
  • byte
  • date
  • date-time
  • password

The column’s format controls the style used when kubectl prints the value.

Subresources

FEATURE STATE: Kubernetes 1.16 stable

This feature is stable, meaning:

  • The version name is vX where X is an integer.
  • Stable versions of features will appear in released software for many subsequent versions.

Custom resources support /status and /scale subresources.

You can disable this feature using the CustomResourceSubresources feature gate on the kube-apiserver:

  1. --feature-gates=CustomResourceSubresources=false

The status and scale subresources can be optionally enabled by defining them in the CustomResourceDefinition.

Status subresource

When the status subresource is enabled, the /status subresource for the custom resource is exposed.

  • The status and the spec stanzas are represented by the .status and .spec JSONPaths respectively inside of a custom resource.
  • PUT requests to the /status subresource take a custom resource object and ignore changes to anything except the status stanza.
  • PUT requests to the /status subresource only validate the status stanza of the custom resource.
  • PUT/POST/PATCH requests to the custom resource ignore changes to the status stanza.
  • The .metadata.generation value is incremented for all changes, except for changes to .metadata or .status.
  • Only the following constructs are allowed at the root of the CRD OpenAPI validation schema:

    • Description
    • Example
    • ExclusiveMaximum
    • ExclusiveMinimum
    • ExternalDocs
    • Format
    • Items
    • Maximum
    • MaxItems
    • MaxLength
    • Minimum
    • MinItems
    • MinLength
    • MultipleOf
    • Pattern
    • Properties
    • Required
    • Title
    • Type
    • UniqueItems

Scale subresource

When the scale subresource is enabled, the /scale subresource for the custom resource is exposed. The autoscaling/v1.Scale object is sent as the payload for /scale.

To enable the scale subresource, the following values are defined in the CustomResourceDefinition.

  • SpecReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Spec.Replicas.

    • It is a required value.
    • Only JSONPaths under .spec and with the dot notation are allowed.
    • If there is no value under the SpecReplicasPath in the custom resource, the /scale subresource will return an error on GET.
  • StatusReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Replicas.

    • It is a required value.
    • Only JSONPaths under .status and with the dot notation are allowed.
    • If there is no value under the StatusReplicasPath in the custom resource, the status replica value in the /scale subresource will default to 0.
  • LabelSelectorPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Selector.

    • It is an optional value.
    • It must be set to work with HPA.
    • Only JSONPaths under .status or .spec and with the dot notation are allowed.
    • If there is no value under the LabelSelectorPath in the custom resource, the status selector value in the /scale subresource will default to the empty string.
    • The field pointed by this JSON path must be a string field (not a complex selector struct) which contains a serialized label selector in string form.

In the following example, both status and scale subresources are enabled.

Save the CustomResourceDefinition to resourcedefinition.yaml:

  1. apiVersion: apiextensions.k8s.io/v1
  2. kind: CustomResourceDefinition
  3. metadata:
  4. name: crontabs.stable.example.com
  5. spec:
  6. group: stable.example.com
  7. versions:
  8. - name: v1
  9. served: true
  10. storage: true
  11. schema:
  12. openAPIV3Schema:
  13. type: object
  14. properties:
  15. spec:
  16. type: object
  17. properties:
  18. cronSpec:
  19. type: string
  20. image:
  21. type: string
  22. replicas:
  23. type: integer
  24. status:
  25. type: object
  26. properties:
  27. replicas:
  28. type: integer
  29. labelSelector:
  30. type: string
  31. # subresources describes the subresources for custom resources.
  32. subresources:
  33. # status enables the status subresource.
  34. status: {}
  35. # scale enables the scale subresource.
  36. scale:
  37. # specReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Spec.Replicas.
  38. specReplicasPath: .spec.replicas
  39. # statusReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Replicas.
  40. statusReplicasPath: .status.replicas
  41. # labelSelectorPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Selector.
  42. labelSelectorPath: .status.labelSelector
  43. scope: Namespaced
  44. names:
  45. plural: crontabs
  46. singular: crontab
  47. kind: CronTab
  48. shortNames:
  49. - ct
  1. # Deprecated in v1.16 in favor of apiextensions.k8s.io/v1
  2. apiVersion: apiextensions.k8s.io/v1beta1
  3. kind: CustomResourceDefinition
  4. metadata:
  5. name: crontabs.stable.example.com
  6. spec:
  7. group: stable.example.com
  8. versions:
  9. - name: v1
  10. served: true
  11. storage: true
  12. scope: Namespaced
  13. names:
  14. plural: crontabs
  15. singular: crontab
  16. kind: CronTab
  17. shortNames:
  18. - ct
  19. validation:
  20. openAPIV3Schema:
  21. type: object
  22. properties:
  23. spec:
  24. type: object
  25. properties:
  26. cronSpec:
  27. type: string
  28. image:
  29. type: string
  30. replicas:
  31. type: integer
  32. status:
  33. type: object
  34. properties:
  35. replicas:
  36. type: integer
  37. labelSelector:
  38. type: string
  39. # subresources describes the subresources for custom resources.
  40. subresources:
  41. # status enables the status subresource.
  42. status: {}
  43. # scale enables the scale subresource.
  44. scale:
  45. # specReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Spec.Replicas.
  46. specReplicasPath: .spec.replicas
  47. # statusReplicasPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Replicas.
  48. statusReplicasPath: .status.replicas
  49. # labelSelectorPath defines the JSONPath inside of a custom resource that corresponds to Scale.Status.Selector.
  50. labelSelectorPath: .status.labelSelector

And create it:

  1. kubectl apply -f resourcedefinition.yaml

After the CustomResourceDefinition object has been created, you can create custom objects.

If you save the following YAML to my-crontab.yaml:

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

and create it:

  1. kubectl apply -f my-crontab.yaml

Then new namespaced RESTful API endpoints are created at:

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

and

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

A custom resource can be scaled using the kubectl scale command. For example, the following command sets .spec.replicas of the custom resource created above to 5:

  1. kubectl scale --replicas=5 crontabs/my-new-cron-object
  2. crontabs "my-new-cron-object" scaled
  3. kubectl get crontabs my-new-cron-object -o jsonpath='{.spec.replicas}'
  4. 5

You can use a PodDisruptionBudget to protect custom resources that have the scale subresource enabled.

Categories

Categories is a list of grouped resources the custom resource belongs to (eg. all). You can use kubectl get <category-name> to list the resources belonging to the category. This feature is beta and available for custom resources from v1.10.

The following example adds all in the list of categories in the CustomResourceDefinition and illustrates how to output the custom resource using kubectl get all.

Save the following CustomResourceDefinition to resourcedefinition.yaml:

  1. apiVersion: apiextensions.k8s.io/v1
  2. kind: CustomResourceDefinition
  3. metadata:
  4. name: crontabs.stable.example.com
  5. spec:
  6. group: stable.example.com
  7. versions:
  8. - name: v1
  9. served: true
  10. storage: true
  11. schema:
  12. openAPIV3Schema:
  13. type: object
  14. properties:
  15. spec:
  16. type: object
  17. properties:
  18. cronSpec:
  19. type: string
  20. image:
  21. type: string
  22. replicas:
  23. type: integer
  24. scope: Namespaced
  25. names:
  26. plural: crontabs
  27. singular: crontab
  28. kind: CronTab
  29. shortNames:
  30. - ct
  31. # categories is a list of grouped resources the custom resource belongs to.
  32. categories:
  33. - all
  1. # Deprecated in v1.16 in favor of apiextensions.k8s.io/v1
  2. apiVersion: apiextensions.k8s.io/v1beta1
  3. kind: CustomResourceDefinition
  4. metadata:
  5. name: crontabs.stable.example.com
  6. spec:
  7. group: stable.example.com
  8. versions:
  9. - name: v1
  10. served: true
  11. storage: true
  12. validation:
  13. openAPIV3Schema:
  14. type: object
  15. properties:
  16. spec:
  17. type: object
  18. properties:
  19. cronSpec:
  20. type: string
  21. image:
  22. type: string
  23. replicas:
  24. type: integer
  25. scope: Namespaced
  26. names:
  27. plural: crontabs
  28. singular: crontab
  29. kind: CronTab
  30. shortNames:
  31. - ct
  32. # categories is a list of grouped resources the custom resource belongs to.
  33. categories:
  34. - all

And create it:

  1. kubectl apply -f resourcedefinition.yaml

After the CustomResourceDefinition object has been created, you can create custom objects.

Save the following YAML to my-crontab.yaml:

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

and create it:

  1. kubectl apply -f my-crontab.yaml

You can specify the category using kubectl get:

  1. kubectl get all

and it will include the custom resources of kind CronTab:

  1. NAME AGE
  2. crontabs/my-new-cron-object 3s

What’s next

Feedback

Was this page helpful?

Thanks for the feedback. If you have a specific, answerable question about how to use Kubernetes, ask it on Stack Overflow. Open an issue in the GitHub repo if you want to report a problem or suggest an improvement.