Home > Backend Development > Golang > How to List Pod Details in Kubernetes using the Go Client?

How to List Pod Details in Kubernetes using the Go Client?

Mary-Kate Olsen
Release: 2024-10-24 19:04:02
Original
742 people have browsed it

How to List Pod Details in Kubernetes using the Go Client?

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:

  1. Import the necessary packages:
<code class="go">import (
    "context"
    "fmt"
    "time"

    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)</code>
Copy after login
  1. Create a function to list pods in the desired 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>
Copy after login
  1. Iterate through the retrieved pods to extract the required data:
<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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template