Home  >  Article  >  Backend Development  >  How to Use the Kubernetes Go Client to Retrieve Detailed Pod Information Like \'kubectl get pods\'?

How to Use the Kubernetes Go Client to Retrieve Detailed Pod Information Like \'kubectl get pods\'?

DDD
DDDOriginal
2024-10-25 05:07:29119browse

How to Use the Kubernetes Go Client to Retrieve Detailed Pod Information Like 'kubectl get pods'?

Kubernetes go-client: Fetching Pod Details Like 'kubectl get pods'

To obtain pod details from a Kubernetes cluster using the Kubernetes client-go, follow these steps:

  1. Create a Pod Interface: Use the client-go's PodInterface to manage pods in a specific namespace.

    <code class="go">podInterface := client.KubeClient.CoreV1().Pods(namespace)</code>
  2. List Pods: Retrieve all pods in the namespace.

    <code class="go">podList, err := podInterface.List(context.TODO(), v1.ListOptions{})</code>
  3. Iterate Over Pods: Iterate through the retrieved pod list to extract specific details like name, status, ready state, restarts, and age.

    <code class="go">for _, pod := range podList.Items {
     // Calculate pod age
     age := time.Since(pod.GetCreationTimestamp().Time).Round(time.Second)
    
     // Get pod status
     podStatus := pod.Status
    
     // Accumulate container stats
     var containerRestarts, containerReady, totalContainers int32
    
     for range pod.Spec.Containers {
         // Add restart count from container status
         containerRestarts += podStatus.ContainerStatuses[container].RestartCount
         // Calculate number of ready containers
         if podStatus.ContainerStatuses[container].Ready {
             containerReady++
         }
         totalContainers++
     }
    }</code>

This approach effectively generates a table similar to the output of 'kubectl get pods -n ' with the desired details, including name, ready state, status, restarts, and age of each pod in the selected namespace.

The above is the detailed content of How to Use the Kubernetes Go Client to Retrieve Detailed Pod Information Like \'kubectl get pods\'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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