Retrieve Pod Details with Kubernetes Go-client
When working within a Kubernetes cluster, it is crucial to have a means of accessing pod details efficiently. The Kubernetes client-go library provides an interface for interacting with the cluster, enabling developers to retrieve a wide range of information.
One common task is to list all pods in a specific namespace, similar to using the kubectl command "kubectl get pods -n
To accomplish this, we utilize the client-go library to interact with the Kubernetes API. The following code snippet demonstrates how to list pods within a given namespace:
<code class="go">func GetPods(client *meshkitkube.Client, namespace string) (*v1core.PodList, error) { podInterface := client.KubeClient.CoreV1().Pods(namespace) podList, err := podInterface.List(context.TODO(), v1.ListOptions{}) if err != nil { return nil, err } return podList, nil }</code>
Once we have retrieved the list of pods, we iterate through each pod and its containers to gather the necessary details:
<code class="go">for _, pod := range podList.Items { podCreationTime := pod.GetCreationTimestamp() age := time.Since(podCreationTime.Time).Round(time.Second) podStatus := pod.Status var containerRestarts int32 var containerReady int var totalContainers int for container := range pod.Spec.Containers { containerRestarts += podStatus.ContainerStatuses[container].RestartCount if podStatus.ContainerStatuses[container].Ready { containerReady++ } totalContainers++ } name := pod.GetName() ready := fmt.Sprintf("%v/%v", containerReady, totalContainers) status := fmt.Sprintf("%v", podStatus.Phase) restarts := fmt.Sprintf("%v", containerRestarts) ageS := age.String() data = append(data, []string{name, ready, status, restarts, ageS}) }</code>
The resulting "data" variable contains an array of string arrays, representing the desired pod details: name, readiness, status, restart count, and age. This data can then be effortlessly printed or manipulated as required.
The above is the detailed content of How to Retrieve Pod Details from a Kubernetes Cluster Using the Go-client Library?. For more information, please follow other related articles on the PHP Chinese website!