List Pod Details with Kubernetes Go-Client
Accessing pod details using the Kubernetes client-go library allows you to programmatically retrieve information similar to using the kubectl get pods command.
To get specific details such as name, status, ready state, restarts, and age of pods within a given namespace, follow these steps:
<code class="go">import ( "context" "fmt" "time" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" )</code>
<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>
<code class="go">// List pod details similar to `kubectl get pods -n <my namespace>` for _, pod := range podList.Items { podCreationTime := pod.GetCreationTimestamp() age := time.Since(podCreationTime.Time).Round(time.Second) podStatus := pod.Status containerRestarts := int32(0) containerReady := 0 totalContainers := len(pod.Spec.Containers) for container := range pod.Spec.Containers { containerRestarts += podStatus.ContainerStatuses[container].RestartCount if podStatus.ContainerStatuses[container].Ready { containerReady++ } } 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 above is the detailed content of How to List Pod Details in Kubernetes using the Go Client?. For more information, please follow other related articles on the PHP Chinese website!