Create the API definition files under the directory structure:
pkg/api/<groupname>/<version>/
Inside this folder, create the following files:
types.go— Define your Custom Resource (CR) Go structs here.doc.go— Package documentation and API group metadata.register.go— Register your types with the scheme.
Use Kubernetes code generators to generate necessary deepcopy functions, clientsets, listers, and informers.
- Ensure you have the boilerplate files such as
boilerplate.go.txt,tools.go, and the scriptupdate-codegen.sh. - Run the code generator script:
bash hack/update-codegen.shThis generates all the required client and deepcopy code based on your API definitions.
Use the controller-gen tool to generate CRD YAML manifests from your API types.
- Install
controller-genif you haven't:
go install sigs.k8s.io/controller-tools/cmd/controller-gen@latest- Generate CRDs and output them to the manifests directory:
go run sigs.k8s.io/controller-tools/cmd/controller-gen crd paths=./pkg/api/... output:crd:dir=./manifests- Implement the reconciliation logic for your controller.
- Define event handlers and business logic to react to changes in your custom resources.
In your main.go:
- Configure the Kubernetes client and clientset.
- Create shared informer factories.
- Initialize your controller.
- Register the controller with the controller-runtime manager.