Last active
February 1, 2022 12:04
-
-
Save PrasadG193/589975a55ed992a7b138a53c3d0d1836 to your computer and use it in GitHub Desktop.
Kubernetes jsonpath golang example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Auto-generated by kyaml2go - https://github.com/PrasadG193/kyaml2go | |
| package main | |
| import ( | |
| "fmt" | |
| "os" | |
| "path/filepath" | |
| "strings" | |
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
| "k8s.io/client-go/kubernetes" | |
| "k8s.io/client-go/tools/clientcmd" | |
| "k8s.io/client-go/util/homedir" | |
| "k8s.io/client-go/util/jsonpath" | |
| "k8s.io/kubectl/pkg/cmd/get" | |
| ) | |
| const ( | |
| DeploymentName = "nginx" | |
| Namespace = "default" | |
| JsonPathFields = ".status.readyReplicas" // OR {.status.readyReplicas} | |
| ) | |
| func main() { | |
| // Create client | |
| var kubeconfig string | |
| kubeconfig, ok := os.LookupEnv("KUBECONFIG") | |
| if !ok { | |
| kubeconfig = filepath.Join(homedir.HomeDir(), ".kube", "config") | |
| } | |
| config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) | |
| if err != nil { | |
| panic(err) | |
| } | |
| clientset, err := kubernetes.NewForConfig(config) | |
| if err != nil { | |
| panic(err) | |
| } | |
| kubeclient := clientset.AppsV1().Deployments(Namespace) | |
| // Manage resource | |
| found, err := kubeclient.Get(DeploymentName, metav1.GetOptions{}) | |
| //fmt.Printf("Found object : %+v\n", found) | |
| if err != nil { | |
| panic(err) | |
| } | |
| // Parse and print jsonpath | |
| fields, err := get.RelaxedJSONPathExpression(JsonPathFields) | |
| if err != nil { | |
| panic(err) | |
| } | |
| j := jsonpath.New("StatusParser") | |
| if err := j.Parse(fields); err != nil { | |
| panic(err) | |
| } | |
| values, err := j.FindResults(found) | |
| valueStrings := []string{} | |
| if len(values) == 0 || len(values[0]) == 0 { | |
| valueStrings = append(valueStrings, "<none>") | |
| } | |
| for arrIx := range values { | |
| for valIx := range values[arrIx] { | |
| valueStrings = append(valueStrings, fmt.Sprintf("%v", values[arrIx][valIx].Interface())) | |
| } | |
| } | |
| fmt.Printf("%s\n", strings.Join(valueStrings, ",")) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment