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:
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>
List Pods: Retrieve all pods in the namespace.
<code class="go">podList, err := podInterface.List(context.TODO(), v1.ListOptions{})</code>
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
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!