标签:type namespace key end string sleep ems ado ror
用来直接获取所有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\n", 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\n%s\n=============\n", 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!\n", file) return } defer f.Close() f.WriteString(str) }
标签:type namespace key end string sleep ems ado ror
原文地址:https://www.cnblogs.com/aguncn/p/11598715.html