Home > Backend Development > Golang > 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
Release: 2024-10-25 05:07:29
Original
299 people have browsed it

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>
    Copy after login
  2. List Pods: Retrieve all pods in the namespace.

    <code class="go">podList, err := podInterface.List(context.TODO(), v1.ListOptions{})</code>
    Copy after login
  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>
    Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template