花了快一天,才搞出来的一个client-go的demo
Posted aguncn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了花了快一天,才搞出来的一个client-go的demo相关的知识,希望对你有一定的参考价值。
用来直接获取所有service的annotaion里有ambassador的东东。
或者,watch集群事件。
package main import ( "fmt" "os" //"time" "strings" //"k8s.io/apimachinery/pkg/api/errors" "k8s.io/api/core/v1" //"k8s.io/apimachinery/pkg/labels" //"k8s.io/apimachinery/pkg/watch" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" // // Uncomment to load all auth plugins // _ "k8s.io/client-go/plugin/pkg/client/auth" // // Or uncomment to load specific auth plugins // _ "k8s.io/client-go/plugin/pkg/client/auth/azure" // _ "k8s.io/client-go/plugin/pkg/client/auth/gcp" // _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" // _ "k8s.io/client-go/plugin/pkg/client/auth/openstack" ) func main() { // creates the in-cluster config config, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } // creates the clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } // get pods in all the namespaces by omitting namespace // Or specify namespace to get pods in particular namespace services, err := clientset.CoreV1().Services("").List(metav1.ListOptions{}) if err != nil { panic(err.Error()) } for i:=0; i < len(services.Items); i++ { item := services.Items[i].Annotations for k, v := range item { if strings.Contains(k, "getambassador") && strings.Contains(v, "ambassador") && strings.Contains(v, "Mapping"){ fmt.Println(v) fmt.Println("@@@@@@@@@@@@@@@@@@@@@@@") } } } //time.Sleep(10 * time.Second) handleNewServices(clientset) } func handleNewServices(clientset *kubernetes.Clientset) { for { serviceStreamWatcher, err := clientset.CoreV1().Services("").Watch(metav1.ListOptions{}) if err != nil { panic(err.Error()) } fmt.Printf("%T ", serviceStreamWatcher) for { select { case event := <-serviceStreamWatcher.ResultChan(): service := event.Object.(*v1.Service) for key, value := range service.Annotations { if strings.Contains(key, "getambassador") && strings.Contains(value, "ambassador") && strings.Contains(value, "Mapping"){ toFileStr := fmt.Sprintf("%s %s ============= ", event.Type, value) //fmt.Println(toFileStr) _appendToFile("/app/k8s-ambassador", toFileStr) } } } } } } func _appendToFile(file, str string) { f, err := os.OpenFile(file, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0664) if err != nil { fmt.Printf("Cannot open file %s! ", file) return } defer f.Close() f.WriteString(str) }
以上是关于花了快一天,才搞出来的一个client-go的demo的主要内容,如果未能解决你的问题,请参考以下文章