Making API Calls

After creating the configuration and clientset, API calls can finally be carried out. All of the Kubernetes resources can be listed, updated, created, or deleted by using the clients in the provided clientset. Some examples are shown in the following code snippet:

// Request all pods from all namespaces
pods, err :=
clientset.CoreV1().Pods(v1.NamespaceAll).List(metav1.ListOptions{})
// Get deployment packt from the default namespace
deployments, err := clientset.AppsV1().Deployments(v1.NamespaceDefault).Get("packt", metav1.GetOptions{})
// Delete statefulset test from namespace packt
clientset.AppsV1().StatefulSets("packt").Delete("test", &metav1.DeleteOptions{})
Code snippets are provided for the configuration, client creation, and making API calls using the Kubernetes Go client in the previous sections. The complete application code is provided in go/main.go, bringing together all of the snippets at https://goo.gl/wJBjG5.

We can note the following points in the main.go file:

  • In the main function that was started at line 19, all of the variables are defined, and the command-line arguments are parsed at line 30.
  • Configuration is created from kubeconfig, and as a fallback method, it is created by in-cluster methods between lines 33 and 42.
  • Clientset is created at line 45.
  • Between lines 51 and 65, an indefinite loop is defined with 10 seconds of sleep at the end of iterations.
  • At every iteration of this loop, pods from all namespaces are requested at line 53. The response is printed to the console between lines 58 and 62.

In the following example, an application combining all of the code snippets in the previous sections is built and run. It shows you how to build a Go application and use it outside the cluster. Although the application seems straightforward, the flow and codebase creates a foundation for complex automation requirements.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.93.141