CustomResourceDefinition (CRD) is an ingenious mechanism introduced in v1.7 that allows you to extend the Kubernetes API without tinkering with code to manage custom objects. Practically speaking, it's an upgraded version of ThirdPartyResources (TPR), which was deprecated in v1.8.
API Version Comparison Table
Kubernetes Version
CRD API Version
v1.8+
apiextensions.k8s.io/v1beta1
CRD Example
The example below crafts a custom API: /apis/stable.example.com/v1/namespaces/<namespace>/crontabs/….
apiVersion:apiextensions.k8s.io/v1beta1kind:CustomResourceDefinitionmetadata:# name must match the spec fields below, and be in the form: <plural>.<group>name:crontabs.stable.example.comspec:# group name to use for REST API: /apis/<group>/<version>group:stable.example.com# versions to use for REST API: /apis/<group>/<version>versions:-name:v1beta1# Each version can be enabled/disabled by the Served flag.served:true# One and only one version must be marked as the storage version.storage:true-name:v1served:truestorage:false# either Namespaced or Clusterscope:Namespacednames:# 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 displaysingular:crontab# kind is normally the CamelCased singular type. Your resource manifests use this.kind:CronTab# shortNames allow a shorter string to match your resource on the CLIshortNames:-ct
Once the API is set up, you can proceed to create specific CronTab objects.
Once the finalizer is indicated, the operation to delete an object by a client will merely set metadata.deletionTimestamp instead of performing a direct deletion. This triggers controllers that are listening to the CRD to perform cleanup operations before deletion, remove its own finalizer from the list, and then initiate a new deletion operation. Only then is the object to be deleted truly eliminated.
Validation
Starting from v1.8, an experimental validation mechanism based on OpenAPI v3 schema was added to validate the conformity of resources submitted by users in advance. To use this function, you need to configure the kube-apiserver's --feature-gates=CustomResourceValidation=true.
For instance, the CRD below necessitates:
spec.cronSpec to be a string that matches a regular expression
spec.replicas to be an integer between 1 and 10
apiVersion:apiextensions.k8s.io/v1beta1kind:CustomResourceDefinitionmetadata:name:crontabs.stable.example.comspec:group:stable.example.comversion:v1scope:Namespacednames:plural:crontabssingular:crontabkind:CronTabshortNames: - ctvalidation:# openAPIV3Schema is the schema for validating custom objects.openAPIV3Schema:properties:spec:properties:cronSpec:type:stringpattern:'^(\d+|\*)(/\d+)?(\s+(\d+|\*)(/\d+)?){4}$'replicas:type:integerminimum:1maximum:10
From v1.10 onwards, CRD also supports two subresources /status and /scale in the beta version, and they are enabled by default from v1.11.
To use in v1.10, you need to enable --feature-gates=CustomResourceSubresources=true on the kube-apiserver.
# resourcedefinition.yamlapiVersion:apiextensions.k8s.io/v1beta1kind:CustomResourceDefinitionmetadata:name:crontabs.stable.example.comspec:group:stable.example.comversion:v1scope:Namespacednames:plural:crontabssingular:crontabkind:CronTabshortNames: - ct# 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
Categories are used to group CRD objects, making it possible to query all objects belonging to that group with kubectl get <category-name>.
# resourcedefinition.yamlapiVersion:apiextensions.k8s.io/v1beta1kind:CustomResourceDefinitionmetadata:name:crontabs.stable.example.comspec:group:stable.example.comversion:v1scope:Namespacednames:plural:crontabssingular:crontabkind:CronTabshortNames: - ct# categories is a list of grouped resources the custom resource belongs to.categories: - all
When extending the Kubernetes API using CRD, it's generally also necessary to implement a controller for the new resources to monitor their changes and make further processing.
As demonstrated above, building a CRD controller from scratch is quite challenging considering the level of understanding required for Kubernetes's API. Integrating RBAC, constructing images, and continuous integration and deployment all demand a large amount of work.
kubebuilder exists to solve this issue, providing an easy-to-use framework for creating CRD controllers and directly generating the resource files needed for image building, continuous integration, and deployment.
Installation
# Install kubebuilderVERSION=1.0.1wget https://github.com/kubernetes-sigs/kubebuilder/releases/download/v${VERSION}/kubebuilder_${VERSION}_linux_amd64.tar.gz
tarzxvfkubebuilder_${VERSION}_linux_amd64.tar.gzsudomvkubebuilder_${VERSION}_linux_amd64/usr/local/kubebuilderexport PATH=$PATH:/usr/local/kubebuilder/bin# Install dep kustomizegoget-ugithub.com/golang/dep/cmd/depgogetgithub.com/kubernetes-sigs/kustomize
Then, depending on your actual needs, modify pkg/apis/ship/v1beta1/sloop_types.go and pkg/controller/sloop/sloop_controller.go to add business logic.
Run Local Test
makeinstallmakerun
If you run into the error ValidationError(CustomResourceDefinition.status): missing required field "storedVersions" in io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.v1beta1.CustomResourceDefinitionStatus], manually modify config/crds/ships_v1beta1_sloop.yaml:
# Replace IMG with your ownexport IMG=feisky/demo-crd:v1makedocker-buildmakedocker-pushmakedeploy
kustomize no longer supports wildcards, so the above make deploy may encounter a Load from path ../rbac/*.yaml failed error. The solution is to manually modify config/default/kustomization.yaml:
resources:
../rbac/rbac_role.yaml
../rbac/rbac_role_binding.yaml
../manager/manager.yaml
Then execute kustomize build config/default | kubectl apply -f - to deploy. By default, it's deployed to the demo-system namespace.
Documentation and Testing
# run unit testsmaketest# generate docskubebuilderdocs