Home > Article > Backend Development > How to Watch CustomResourceDefinitions (CRDs) with Client-Go?
Watch CustomResourceDefinitions (CRDs) with Client-Go
CustomResourceDefinitions (CRDs) extend Kubernetes' core API to allow users to create and manage their own resource types. To watch for changes to CRDs, you can utilize client-go, a Kubernetes client library.
Client-Go for Standard Resources
Client-go provides a straightforward mechanism to watch for changes in standard resources like Services. The following example demonstrates how to watch for new or modified Services:
<code class="go">import ( "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" ) func handleNewServices(clientset *kubernetes.Clientset) { for { serviceStreamWatcher, err := clientset.CoreV1().Services("").Watch(metav1.ListOptions{}) if err != nil { panic(err.Error()) } // Process events // ... } }</code>
Extending Client-Go for CRDs
Client-go does not natively recognize CRDs. To support them, you need to generate a client for your custom resources. Kubernetes provides code-generation tools for this purpose.
For instance, to create a client for the ApiGateway CRD defined in the provided snippet, follow the steps outlined in [this blog post](link to blog post).
Code Generation
Generate the client: Run the following command, replacing your-group with the group of your CRD:
client-gen --input-base "" --input your-group/v1 --output-base ./pkg --output-package pkg/clientset/versioned --clientset-name versioned
This will generate the necessary API and client structs in the pkg directory.
Controller Example
Refer to [this sample controller](link to sample controller) for an example of how to watch for your CRD using the generated client. The example_controller package contains the code to handle watch events.
Kubebuilder
To simplify the process of generating client configs and controllers for CRDs, you can use [kubebuilder](link to kubebuilder). This tool automates many of the steps described above.
The above is the detailed content of How to Watch CustomResourceDefinitions (CRDs) with Client-Go?. For more information, please follow other related articles on the PHP Chinese website!