在 Go 中實作自訂控制器之前,我們首先了解什麼是 Kubernetes 控制器和客戶資源定義 (CRD)
Kubernetes 控制器是控制平面的元件,它持續監視 kubernetes 叢集的狀態並採取行動以確保叢集的實際狀態與所需狀態相符。它會進行更改,試圖使當前狀態更接近所需狀態。
自訂資源定義(CRD)是一種擴展 Kubernetes API 以建立我們自己的自訂資源的方法。這些自訂資源可以代表我們想要在 Kubernetes 叢集中管理的任何類型的物件。
apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: my-crds.com.shivam.kumar spec: group: com.shivam.kumar names: kind: my-crd plural: my-crds scope: Namespaced versions: - name: v1 served: true storage: true schema: openAPIV3Schema: type: object properties: apiVersion: type: string kind: type: string metadata: type: object spec: type: object properties: description: type: string
使用 kubectl 指令套用此文件,當我們在叢集中看到可用的 crd 時,我們可以看到我們建立的 crd -
apiVersion: com.shivam.kumar/v1 kind: my-crd metadata: name: my-custom-resource spec: description: "My CRD instance"
使用 kubectl 指令套用此檔案
現在讓我們繼續建立自己的自訂控制器
package main import ( "context" "fmt" "path/filepath" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/dynamic" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" ) func main() { var kubeconfig string if home := homedir.HomeDir(); home != "" { kubeconfig = filepath.Join(home, ".kube", "config") } config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) if err != nil { fmt.Println("Falling back to in-cluster config") config, err = rest.InClusterConfig() if err != nil { panic(err.Error()) } } dynClient, err := dynamic.NewForConfig(config) if err != nil { panic(err.Error()) } thefoothebar := schema.GroupVersionResource{Group: "com.shivam.kumar", Version: "v1", Resource: "my-crds"} informer := cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return dynClient.Resource(thefoothebar).Namespace("").List(context.TODO(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return dynClient.Resource(thefoothebar).Namespace("").Watch(context.TODO(), options) }, }, &unstructured.Unstructured{}, 0, cache.Indexers{}, ) informer.AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { fmt.Println("Add event detected:", obj) }, UpdateFunc: func(oldObj, newObj interface{}) { fmt.Println("Update event detected:", newObj) }, DeleteFunc: func(obj interface{}) { fmt.Println("Delete event detected:", obj) }, }) stop := make(chan struct{}) defer close(stop) go informer.Run(stop) if !cache.WaitForCacheSync(stop, informer.HasSynced) { panic("Timeout waiting for cache sync") } fmt.Println("Custom Resource Controller started successfully") <-stop }
現在,當我們建立這個 Go 程式並運行它時 -
go build -o k8s-controller .
./k8s-控制器
現在,每當我們新增、更新或刪除上面建立的自訂資源時,我們都會在終端機中取得它的活動日誌。所以這意味著我們的控制器正在監視我們的 CRD。
以上是在 Go 中建立自訂 Kubernetes 控制器的詳細內容。更多資訊請關注PHP中文網其他相關文章!